I am trying to load an image inside a function, but the image is not showing on the screen. There are no console errors so i don’t know why it will not work.
Code:
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var score = 0;
var menuImg = new Image();
menuImg.src = "images/Startscreen.png";
gamemenu();
//The menu screen
function gamemenu(){
ctx.drawImage(menuImg,0,0);
}
The image should draw when the function is called but it does not, any help?
Loading an image is an asynchronous process so you need to add an event handler for the “load” event.
I deal with this on a regular basis in my projects since we make heavy use of canvas and sprite rendering.
Update: Here’s MDN’s page about this topic.