HTML canvas drawImage () method
To use the picture:
Examples
To draw a picture on top of the canvas:
JavaScript:
var ctx = c.getContext ( "2d");
var img = document.getElementById ( "scream");
img.onload = function () {
ctx.drawImage (img, 10,10);
}
try it"
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome and Safari support drawImage () method.
Note: 8 and earlier versions of Internet Explorer do not support the <canvas> element.
Definition and Usage
drawImage () method to draw an image, video or canvas on the canvas.
Certain portions to drawImage () method can also draw the image, and / or increase or decrease the size of the image.
JavaScript syntax
Positioning the image on the canvas:
JavaScript syntax: | context .drawImage (img, x, y); |
---|
Positioning the image on the canvas, and a predetermined width and height of the image:
JavaScript syntax: | context .drawImage (img, x, y, width, height); |
---|
Cut image and localize the cut portion on canvas:
JavaScript syntax: | context .drawImage (img, sx, sy, swidth, sheight, x, y, width, height); |
---|
Parameter Value
parameter | description | |
---|---|---|
img | Predetermined image, canvas or video you want to use. | |
sx | Optional. Start cutting the x coordinate of the position. | |
sy | Optional. Start cut y coordinates. | |
swidth | Optional. It is the width of the cut image. | |
sheight | Optional. Highly cut image. | |
x | Place x coordinate position of the image on the canvas. | |
y | Place y coordinates of the position of the image on the canvas. | |
width | Optional. To use the width of the image (by stretching or shrinking the image). | |
height | Optional. The height of the image you want to use (by stretching or shrinking the image). |
More examples
Examples
On the canvas the image positioning, then specify the width and height of the image:
JavaScript:
var ctx = c.getContext ( "2d");
var img = document.getElementById ( "scream");
img.onload = function () {
ctx.drawImage (img, 10,10,150,180);
}
try it"
Examples
Cut the picture, and on the canvas of the sheared portions are positioned:
JavaScript:
var ctx = c.getContext ( "2d");
var img = document.getElementById ( "scream");
ctx.drawImage (img, 90,130,50,60,10,10,50,60);
try it"
Examples
Video you want to use (press the play button to start the demo):
canvas:
JavaScript (every 20 milliseconds, the code will draw a current frame of video):
var c = document.getElementById ( "myCanvas");
ctx = c.getContext ( '2d');
v.addEventListener ( 'play', function () {var i = window.setInterval (function () {ctx.drawImage (v, 5,5,260,125)}, 20);}, false);
v.addEventListener ( 'pause', function () {window.clearInterval (i);}, false);
v.addEventListener ( 'ended', function () {clearInterval (i);}, false);
try it"
HTML canvas Reference Manual