Reputation: 12598
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
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