Aidan Lawrence Aidan Lawrence - 2 months ago 8
Javascript Question

Why won't the first function continue on to the rest?

I'm pretty new to JS, and have just run into my first roadblock. The canvasLoad() function is called upon a HTML page loading, but it will not do anything unless I comment out all of the other functions.It is supposed to display a small icon inside a canvas.

I have tested that the canvasLoad() function works properly by commenting out all the other functions, and it works fine then.

var c;

function canvasLoad() {
var gCanvas = document.getElementById("gameCanvas");
c = gCanvas.getContext("2d");

c.fillRect(20,20,400,400);

srcImage();
}

var image;

function srcImage() {
image = new Image();
image.src = "icon.png";

imgDraw();
}

function imgDraw() {
c.clearRect(0, 0, 400, 400);

c.drawImage(image, 10, 10);
}

Answer

Images are loaded via HTTP request, and that takes time. You should set up imgDraw() as a "load" event handler:

function srcImage() {
    image = new Image();
    image.onload = imgDraw;
    image.src = "icon.png";
}

The browser will invoke the function upon completion of that HTTP request.

Comments