fightstarr20
fightstarr20

Reputation: 12598

HTML canvas not drawing image from file

I am trying to load an image from a file and draw it on a canvas. I have this..

const canvas  = document.createElement("canvas");
const context = canvas.getContext("2d");

myImage = new Image();
myImage.src = "img/image.jpg";

context.drawImage(myImage, 0, 0, 100, 100);

This is not drawing anything on the screen, where am I going wrong? I can see the image being loaded by developer tools so I know that it can find the file itself.

Upvotes: 1

Views: 88

Answers (1)

Kostas Minaidis
Kostas Minaidis

Reputation: 5412

If the canvas element is already on the page, you'll need to replace the createElement method with querySelector:

// const canvas  = document.createElement("canvas");
const canvas  = document.querySelector("canvas");
const context = canvas.getContext("2d");

myImage = new Image();
myImage.src = "img/image.jpg";

myImage.addEventListener("load", ()=>{
  context.drawImage(myImage, 0, 0, 100, 100);
}); // Thanks to Xion 14 for the reminder!

Otherwise, you'll need to append the canvas element to the DOM, e.g. via document.body.appendChild( canvas );

Upvotes: 1

Related Questions