drawImage method
Draws a specified image onto a canvas.
Syntax
object.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
Parameters
image [in]
Type: objectAn img, canvas, or video element of the pattern to use.
sx [in, optional]
Type: numberThe horizontal starting value (x), in CSS pixels, relative to the source image.
sy [in, optional]
Type: numberThe vertical starting value (y), in CSS pixels, relative to the source image.
sw [in, optional]
Type: numberThe width of the source image, in CSS pixels, to draw onto the canvas.
sh [in, optional]
Type: numberThe height of the source image, in CSS pixels, to draw onto the canvas.
dx [in]
Type: numberThe horizontal (x) value, in CSS pixels, where to place the image on the canvas.
dy [in]
Type: numberThe vertical (y) value, in CSS pixels, where to place the image on the canvas.
dw [in, optional]
Type: numberThe destination width value, in CSS pixels, to use when drawing the image to the canvas.
dh [in, optional]
Type: numberThe destination height value, in CSS pixels, to use when drawing the image to the canvas.
Return value
This method does not return a value.
Exceptions
The following exceptions can be thrown.
Exception | Condition |
---|---|
TypeMismatchError | The image parameter is not an img object, canvas element, or video element. Versions earlier than Internet Explorer 10 use TYPE_MISMATCH_ERR. |
InvalidStateError | The image parameter does not contain image data. Versions earlier than Internet Explorer 10 use INVALID_STATE_ERR. |
IndexSizeError | The numeric arguments are not valid (for example, the destination is a 0x0 rectangle). Versions earlier than Internet Explorer 10 use INDEX_SIZE_ERR. |
SecurityError | The img or video element is not of the same origin or domain as the document that owns the canvas element. Versions earlier than Internet Explorer 10 use SECURITY_ERR. |
Standards information
- HTML Canvas 2D Context, Section 12
Remarks
The ICanvasRenderingContext2D::drawImage method provides three ways to draw an image onto a canvas, depending on how you use the optional parameters:
- drawImage(image,dx,dy) copies an image exactly to the canvas at the location that the dx and dy parameters specify.
- drawImage(image,dx,dy,dw,dh) copies an image to the canvas by using the dw and dh parameters to stretch or reduce the image. This option is similar to the size attributes on an img tag.
- drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh) copies all or part of a source image to the canvas. You can place and size the destination image by using the destination parameters.
If you do not specify the dw and dh parameters, they equal the values of sw and sh. One CSS pixel in the image is treated as one unit in the canvas coordinate space.
Note If you're specifying an image, be sure the image content has loaded fully if you're calculating the width and height of the img tag.