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:

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:

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!

Facebook Comments