Why is it so difficult to check if an img has loaded in JavaScript? With other languages this can be easily solved by doing a loop, and breaking when the image has loaded.
Here is a function that returns a loaded img after passing a file path. Nothing other than onload seems to work to check if the image has loaded. I am unable to use img.complete or any other method with a loop checking each time until the load has completed because it simply does not work (the browser will hang).
global_image_loaded = 0
function LOADIMAGE(imagesrc) {
global_image_loaded = 0
var img = new Image();
img.src = imagesrc + "?" + new Date().getTime();
img.onload = function() {
global_image_loaded = 1;
}
if ( global_image_loaded = 1 ){
return img;
} else {
return 0;
}
}
This function works fine, until I try to draw the image to canvas with the following function:
function IMAGE(elementid, img, x, y, w, h) {
var mode = 0;
if ( w === undefined) {
mode = 1;
}
if ( h === undefined) {
mode = 1;
}
var canvas = document.getElementById(elementid);
if ( ! canvas || ! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
if ( mode === 1) {
ctx.drawImage(img, x, y);
}
if (mode === 0) {
ctx.drawImage(img, x, y, w, h);
}
}
This function works too but only if placed inside a loop, and ran several times. The image will display on the canvas, but it won't load an image when executed once. How can this even be possible, hasn't the img loaded already?
I think this is how it's done in JavaScript, unfortunately the img cannot be returned, and needs to always be displayed right afterwards? There seems to be no way to arbitrarily display an image.
function PLACEIMAGE(elementid, imagesrc, x, y, w, h) {
var mode = 0;
if ( w === undefined) {
mode = 1;
}
if ( h === undefined) {
mode = 1;
}
var canvas = document.getElementById(elementid);
if ( ! canvas || ! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = imagesrc + "?" + new Date().getTime();
img.onload = function() {
if ( mode === 1) {
ctx.drawImage(img, x, y);
}
if (mode === 0) {
ctx.drawImage(img, x, y, w, h);
}
};
}