JavaScript: Add image to canvas.

This is a short guide on how to add an image to a canvas element using JavaScript. In this tutorial, I will be using simple vanilla JavaScript.

The canvas element.

In this case, we have a simple canvas element with the ID my_canvas:

<canvas id="my_canvas" width="400" height="400"></canvas>

The canvas element above is 400 pixels in both width and height.

Adding an image to the canvas element.

Now, let’s take a look at the following JavaScript snippet:

//Get the canvas element by using the getElementById method.
var canvas = document.getElementById('my_canvas');

//Get a 2D drawing context for the canvas.
var context = canvas.getContext('2d');

//The path to the image that we want to add.
var imgPath = 'test.jpg';

//Create a new Image object.
var imgObj = new Image();

//Set the src of this Image object.
imgObj.src = imgPath;

//the x coordinates
var x = 0;

//the y coordinates
var y = 0;

//When our image has loaded.
imgObj.onload = function(){
    //Draw the image onto the canvas.
    context.drawImage(imgObj, x, y);
}

In the code above:

  1. We got the canvas element by using the getElementById() method.
  2. We created a 2D drawing context for this canvas by using the HTMLCanvasElement.getContext() method. In this case, we want a 2D context type. Other types such as “webgl” and “bitmaprenderer” can also be used.
  3. After that, we created a JavaScript Image object and specified the src attribute. In this case, the src is an image file called “test.jpg”. You will obviously need to modify this part of the code to reference your image path.
  4. We set the x-axis and y-axis coordinates, which will be used by our context object to place the image. In this case, I have set both to 0, which means that the image will be added to the top-left hand corner of the canvas. You can play around with these values to get a better understanding of how they work.
  5. Finally, after the image has been properly loaded, we use the drawImage() method to “draw” our image onto the canvas. The onload event handler is important, as your code will not work if you try to add an image that hasn’t been loaded yet! If this image is vitally important, then you could preload it at the start of your application.

And that’s it!