Drawing Images
The drawImage() method allows you to render images, such as photos or other canvas elements, directly onto the canvas.
There are three ways to use drawImage() depending on whether you want to do basic drawing, scaling, or cropping:
| Syntax | Description |
|---|---|
drawImage(image, dx, dy) |
Draws the image at the specified destination (dx, dy) at its original size. |
drawImage(image, dx, dy, dWidth, dHeight) |
Draws the image at the destination (dx, dy) and scales it to the specified width and height. |
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) |
Crops the source image (starting at sx, sy with dimensions sWidth, sHeight) and then draws/scales it at the destination coordinate. |
Image Sources
The image parameter can be several types of objects:
- An
HTMLImageElement(created vianew Image()or by referencing animgelement). - An
HTMLVideoElement(referencing avideoelement). - Another
HTMLCanvasElement.
Image Example
To draw an image, it must first be loaded. Use an onload event listener to ensure the image data is available before calling drawImage():
CORS and Tainted Canvas
If you load an image from a different domain, you might encounter issues if you later try to read pixel data from the canvas (e.g., using getImageData()). This security feature is known as a "tainted canvas."
The next lesson explains how to manage the canvas state, which is useful for complex drawings and transformations.