0

I'm trying to load an image to a canvas inside a function but when I start the code the image doesn't load but when the function is called again the image load. Can anyone tell me what's wrong?

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const foodImg = new Image();
foodImg.src = "img/food.png";

start();

function start()
{
//code
ctx.drawImage(foodImg, xFood, yFood, size, size);
}
Golden
  • 93
  • 9
  • My initial thought would be that the image isn't loaded yet: https://stackoverflow.com/questions/280049/how-to-create-a-javascript-callback-for-knowing-when-an-image-is-loaded - try to call `start()` when the image is actually loaded. – Caramiriel Feb 14 '20 at 15:54
  • Try `foodImg.addEventListener("load", start);`. – Daemon Beast Feb 14 '20 at 16:01

0 Answers0