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.
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, eg via document.body.appendChild( canvas );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.