The CanvasRenderingContext2D
.drawImage()
method of the Canvas 2D API provides different ways to draw an image onto the canvas.
void ctx.drawImage(image, dx, dy); void ctx.drawImage(image, dx, dy, dWidth, dHeight); void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
image
CanvasImageSource
), such as an HTMLImageElement
, an HTMLVideoElement
, an HTMLCanvasElement
or an ImageBitmap
.dx
image
.dy
image
.dWidth
image
in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in width when drawn.dHeight
image
in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in height when drawn.sx
sy
sWidth
sx
and sy
to the bottom-right corner of the image is used.sHeight
INDEX_SIZE_ERR
INVALID_STATE_ERR
TYPE_MISMATCH_ERR
drawImage
methodThis is just a simple code snippet which uses the drawImage
method.
<canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227"> </div>
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = document.getElementById('source'); ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
Edit the code below and see your changes update live in the canvas:
Specification | Status | Comment |
---|---|---|
WHATWG HTML Living Standard The definition of 'CanvasRenderingContext2D.drawImage' in that specification. | Living Standard |
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
ImageBitmap as source image | ? | No support | 42 (42) | ? | ? | ? |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
ImageBitmap as source image | ? | ? | No support | 42.0 (42) | ? | ? | ? |
sw
and sh
was added in Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2).drawImage()
handles negative arguments in accordance with the specification, by flipping the rectangle around the appropriate axis.null
or undefined
image when calling or drawImage()
correctly throws a TYPE_MISMATCH_ERR
exception starting with (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2).HTMLVideoElement
when its HTMLMediaElement.readyState
is greater than 1 (i.e, seek event fired after setting the currentTime property)CanvasRenderingContext2D
.
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage