Through the previous study, we can now draw graphics and text in HTML5Canvas and set some styles for them. We can also draw images in the canvas .,.
HTML5 CANVAS: draw an image
Through the previous study, we can now draw graphics and text in HTML5 canvas and set some styles for them. We can also . Used in The source image can be of the following element types:
HTMLImageElement: an Image created by the Image () constructor or any element.
HTMLVideoElement: use an HTML The element is used as the image source, and the current frame is captured from the video as the image source.
HTMLCanvasElement: You can also use another The element is used as the image source.
Draw Images
We can use three methods of 2D context
DrawImage (image, dx, dy );
DrawImage (image, dx, dy, dw, dh );
DrawImage (image, sx, sy, sWidth, sHeight, dx, dy, dw, dh );
Basic image Rendering Method: drawImage (image, dx, dy)
This method is in
The following is an example. In this example
var ctx = document.getElementById('ex1').getContext('2d');var img = new Image();img.onload = function(){ ctx.drawImage(img,0,0);};img.src = 'img/canvas-image-1.jpg';
The returned results of the above Code are as follows:
In the following example, we reduced the image size by about 1/3 and arranged it to form a grid.
var ctx = document.getElementById('ex2').getContext('2d');var img = new Image();img.onload = function(){ for (var i=0;i<4;i++){ for (var j=0;j<5;j++){ ctx.drawImage(img,j*60,i*60,60,60); } }};img.src = 'img/canvas-image-2.jpg';
The returned results of the above Code are as follows:
Let's take a look at the example below. In this example, we cut a part of the source image and draw it on a canvas border image.
Var canvas = document. getElementById ('ex3'); var ctx = canvas. getContext ('2d '); // draw an image slice ctx. drawImage (document. getElementById ('source'), 98,205,104,124, 21, 20, 87,104); // draw the border image ctx. drawImage (document. getElementById ('framework'), 0, 0 );
The result of the above Code is as follows:
Before you can draw an Image in the Canvas, you need to create an Image object and load the Image to the memory. The following is the js Code that completes this operation:
var image = new Image();image.src = "img/sample.png";
Before you can draw an image, the image must be fully loaded. To ensure that the image is fully loaded, you can add an event listener for the image. The method in this event listener will be called after the image is fully loaded. The following is an example code:
image.addEventListener('load', drawImage1);
Or:
var img = new Image();img.onload = function(){ ctx.drawImage(img,0,0);};
The above is the HTML5 CANVAS: The image content. For more information, see the PHP Chinese Network (www.php1.cn )!