HTML canvas drawImage()
Method
Image to be Used:
Example
Drawing an image onto the canvas:
JavaScript:
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the drawImage()
method.
Note: Internet Explorer 8 and earlier versions do not support the <canvas>
element.
Definition and Usage
The drawImage()
method draws an image, canvas, or video onto the canvas.
The drawImage()
method can also draw parts of an image, and/or increase or decrease the image size.
JavaScript Syntax
Positioning an image on the canvas:
| JavaScript Syntax: | context.drawImage(img, x, y); | | --- | --- |
Positioning an image on the canvas and specifying the image's width and height:
| JavaScript Syntax: | context.drawImage(img, x, y, width, height); | | --- | --- |
Cropping an image and positioning the cropped part on the canvas:
| JavaScript Syntax: | context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height); | | --- | --- |
Parameter Values
Parameter | Description |
---|---|
img | Specifies the image, canvas, or video to use. |
sx | Optional. The x coordinate where to start cropping. |
sy | Optional. The y coordinate where to start cropping. |
swidth | Optional. The width of the cropped image. |
sheight | Optional. The height of the cropped image. |
x | The x coordinate where to place the image on the canvas. |
y | The y coordinate where to place the image on the canvas. |
width | Optional. The width of the image to use (stretches or shrinks the image). |
height | Optional. The height of the image to use (stretches or shrinks the image). |
More Examples
Example
Positioning an image on the canvas and specifying the image's width and height:
JavaScript:
Example
Cropping an image and positioning the cropped part on the canvas:
JavaScript:
Example
Using a video (press the play button to start the demonstration):
Canvas:
JavaScript (draws the current frame of the video every 20 milliseconds):