Skip to content

Instantly share code, notes, and snippets.

@ManishPoduval
Last active September 23, 2020 10:27
Show Gist options
  • Save ManishPoduval/7150ddad5a1f45239b3d27b58b1009cf to your computer and use it in GitHub Desktop.
Save ManishPoduval/7150ddad5a1f45239b3d27b58b1009cf to your computer and use it in GitHub Desktop.
Canvas images

How to use images on canvas?

Step 1: create image tag withnew Image()

We will start with creating image tag, and the following line of code does exactly that:

let naturePic = new Image();
console.log("what is this: ", naturePic);

// what is this: <img>

In the console in the browser we can see that the image tag has been created (<img>).

Step 2: add file to the src of the newly created <img> tag

Image tag lives in the HTML file (we use JS to create it, but it doesn't live here in index.js but in index.html).This is important to understand because when we link the photos, the path to the photo needs to be from the index.html to images folder, and these two are on the same level in the tree, meaning in the structure of our root folder:

.
├── images
│    └── waterfalls.jpeg
├── index.html
└── js
     └── index.js

This being said, we link image to the src as it shows below:

naturePic.src = "./images/waterfalls.jpeg";
console.log("and what is this: ", naturePic);

// and what is this:  <img src=​"./​images/​waterfalls.jpeg">​

Step 3: make image appear on canvas

Now image is there, we just need to make it to appear on the canvas:

naturePic.addEventListener('load', function(){
    ctx.drawImage(naturePic, 10, 10, 260, 160)
})

or another way to add a load event listener is

naturePic.onload = () => {
  ctx.drawImage(naturePic, 10, 10, 260, 160);
};

And here is the image on the canvas!

Additional explanation of why it is important to know that index.html and images folder are on the same level in the structure of folder and files:

When linking the photo to the src, if we would link photo from this file (and we are in the js/index.js) the path to the image would be:

naturePic.src = "../images/waterfalls.jpeg";

This means we have to exit js folder (that's why two dots ../) to be able to see images folder.

However, when we link it we use only single dot (./):

naturePic.src = "./images/waterfalls.jpeg";

since images folder is on the same level as index.html.

Great, now you know how to use images in canvas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment