Saturday, 13 September 2014

HTML5 - Mastering the Canvas Element (VIII) - Using images with canvas


Okay, after some grave violation of grammar and "drawing" text on your canvas, let's now talk about drawing images on the canvas element.

This can be really useful if you're building a game or something where you'll need to import images and animate them on your canvas.


All you need to know about canvas.drawImage function

Canvas treats images as shapes too. Just like you draw rectangles and text, you also draw images using the drawImage function.

This function takes in the following parameters:

  • image: This parameter is an Image() object that I'll talk about in more detail in the next section of this tutorial. This basically refers to the image that we'll be drawing on the canvas.
    Required
  • x: The x coordinate of the image.
    Required
  • y: The y coordinate of the image.
    Required
  • width: The width of the image.
    Optional
  • height: The height of the image.
    Optional
So here's an example usage of the function:
context.drawImage(img, 0, 0, 100, 100);

About the image object

To create an image object in JavaScript, you simply do this:
var img = new Image();
To actually point some image to this variable you simple put in the URL of the image in the src property of the image variable.
img.src = "http://example.com/path/to/image/file.png";
You can then draw this image on the canvas using what I taught you above. You simple pass this variable as the first variable of the function

Conclusion

So, now that you've learnt all about drawing stuff on the canvas, and that's pretty much it! You've mastered the canvas element!

No comments:

Post a Comment