Drawing an image

Let's jump right in by drawing a simple image. In this recipe, we'll learn how to load an image and draw it somewhere on the canvas.

Drawing an image

Follow these steps to draw an image in the center of the canvas:

How to do it...

  1. Define the canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Create an image object, set the onload property to a function that draws the image, and then set the source of the image:
     var imageObj = new Image(); imageObj.onload = function(){ var destX = canvas.width / 2 - this.width / 2; var destY = canvas.height / 2 - this.height / 2; context.drawImage(this, ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.