I think I'm having a similar issue to this question, but I would like a little help understanding how to use a callback function and how to implement it for my particular situation. I'm trying to have an image get drawn to a canvas "on demand", i.e. any time a certain function is called. The image is associated with an object I call a Block. A Block has dimensions, coordinates, and a url.
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function Block(x, y, width, height, url) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.url = url;
this.drawBlock = drawBlock;
function drawBlock() {
var blockSprite = new Image();
blockSprite.src = url;
blockSprite.onload = context.drawImage(blockSprite,x,y,width,height);
}
}
You can see a demo here. Oddly enough, it works if I link to an image on the web, but fails if I link to an image on my disk. I believe that this is because the onload event occurs before drawBlock is called, and that I need to use callbacks or promises to fix this, but I'm very new to Javascript so I'd like a little guidance here. Any help or advice would be appreciated.
Try it this way:
A callback is simply a function that is executed at a later time--usually after a long-running task has finally been completed.
Loading an image is a good example. Consider this code:
It will actually execute in this order:
The image object is created.
var image=new Image();
The image object is told that when it's done fully loading the image it should execute the function called someCallbackFunction.
image.onload=someCallbackFunction
The image is given a .src URL and begins the long process of downloading the image
image.src="yourImage.png";
Any code after image.src="yourImage.png" will execute.
...Sometime later...After the image is fully loaded, the image object will execute someCallbackFunction() and the alert will sound.