A canvas element may be used to draw images too.

There is only one method needed for drawing an image and that is drawImage() method. However before evoking the method, an image object has to be loaded in order to be associated with it. One common way of doing so is using the onload event or property of the image object (see example).

The drawImage() method may accept three, five, or nine arguments:

  • drawImage(image, dx, dy) - the method takes an image and draws it on the canvas; dx and dy are coordinates describing where to start drawing and image at, with (0,0) being the upper-left corner
  • drawImage(image, dx, dy, dw, dh) - the method takes an image, scales it to a width of dw and a height of dh, and draws it on the canvas at coordinates (dx, dy)
  • drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) - the method takes an image, clips it to the rectangle defined with (sx, sy, sw, sh), scales it to dimensions (dw, dh), and draws it on the canvas at coordinates (dx, dy)

Example

Using canvas element to draw a canvas image:

 

›› go to examples ››