Use the drawImage method of Canvas, canvasdrawimage
Canvas is a new element in html5. this element can be used to draw images through JavaScript. For example, you can use it to draw images, synthesize images, and make some animations.
Generally, we use an Image object to draw images on a canvas. Basically, some typical image formats (png, jpg, and gif) are correct. Okay, then let's use it.
1 var canvas=document.getElementById("game_canvas");2 var cxt=image.getContext("2d");3 var image=new Image();4 img.src="./res/background.jpg";
This is part of my code for a recent project. to render this background image to a canvas, you must use the drawImage method. The format of this method is as follows:
drawImage(image,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight);
The first parameter is the image object to be cropped, and s represents the source, that is, the meaning of "source material. D Represents the dest, that is, the layout on the canvas. Sx and sy are the starting point for image cropping. sWidth and sHeight are the image cropping sizes. It is worth mentioning that I tried to use the percentage and found it was not feasible. Dx and dy are the positions in the upper left corner of the cropped image and the upper left corner of the canvas. dWidth and dHeight represent the scaled size. This product seems to only accept pixels as units. For example, the size of the image below is 800*600.
I perform the following operations on it:
ctx.drawImage(image,0,0,image.width,image.height,0,0,200,400);
First, I cropped it completely, and then scaled it to 200,400. When measured in the browser, it became
That is to say, it forcibly scales the width and height to 200*400, even if the image has been deformed.