Latest web development tutorials

HTML canvas drawImage () method

Canvas Object Reference Canvas object

To use the picture:

The Scream

Examples

To draw a picture on top of the canvas:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);

try it"

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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

参数 描述
img 规定要使用的图像、画布或视频。
sx 可选。开始剪切的 x 坐标位置。
sy 可选。开始剪切的 y 坐标位置。
swidth 可选。被剪切图像的宽度。
sheight 可选。被剪切图像的高度。
x 在画布上放置图像的 x 坐标位置。
y 在画布上放置图像的 y 坐标位置。
width 可选。要使用的图像的宽度(伸展或缩小图像)。
height 可选。要使用的图像的高度(伸展或缩小图像)。


Examples

More examples

Examples

On the canvas the image positioning, then specify the width and height of the image:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10,150,180);

try it"

Examples

Cut the picture, and on the canvas of the sheared portions are positioned:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
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:

yourbrowserdoesnotsupportthecanvastag

JavaScript (every 20 milliseconds, the code will draw a current frame of video):

var v=document.getElementById("video1");
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"


Canvas Object Reference Canvas object