how to load image to canvas using javascript
Javascript Web Development

How to Load Image to Canvas with JavaScript

Canvas is an element for drawing graphic on webpage with JavaScript which responsible for majority of stunning effect on today’s website. In this tutorial, we’ll show you how to load an existing image to canvas with JavaScript, which could be further used for image processing or pixel manipulation down the road.

Suppose that we have an image one webpage like this one.

<img id="image1" src="image1.jpg" />

First, we dynamically create a canvas object and get the 2D rendering context (or you can reuse one if you already have it)

let c = document.createElement("canvas");
ctx = c.getContext('2d');

Then create an Image object. We’re going to use load our image to this Image object and pass it to the canvas.

let img1 = new Image();

But we can’t simply load it and continue the process like this. That won’t work because loading image is a non-blocking code. JavaScript will execute the next line immediately even though the loading has not finished yet.

//THIS WON"T WORK!!

let img1 = new Image();
img1.src = document.getElementById("image1").src;

//continue canvas processing

We need to bind the onload event listener to start passing image data to the canvas AFTER the loading has finished like so.

//THIS IS THE CORRECT EXAMPLE

let img1 = new Image();

img1.onload = function () {
  //continue canvas procesing after image has been loaded
};

img1.src = document.getElementById("image1").src;

Then we’ll set the canvas dimension to be the same as image (or bigger if you want) and load the image to canvas using drawImage method.

img1.onload = function () {
      c.width = img1.width;
      c.height = img1.height;
      ctx.drawImage(img1, 0, 0);
}

And that’s it! The image is ready on the canvas for processing! You can download the source code of this tutorial here.

Written By

One comment

  1. Hello, I downloaded your files and test Front End Projects. Then I found the error on lines 36 says about:

    index.html:36 Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.
    at Image.img1.onload (file:///D:/load%20image%20to%20canvas/index.html:36:20)

    So that’s why I hope you can fix this error soon and success. Thank you very much for your projects. It’s nice.

Leave a Reply

Your email address will not be published. Required fields are marked *