Why does JavaScript make it so difficult to check if an image is loaded? -
why difficult check if img has loaded in javascript? other languages can solved doing loop, , breaking when image has loaded.
here function returns loaded img after passing file path. nothing other onload seems work check if image has loaded. unable use img.complete or other method loop checking each time until load has completed because not work (the browser 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 try draw image canvas 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 if placed inside loop, , ran several times. image display on canvas, won't load image when executed once. how can possible, hasn't img loaded already?
i think how it's done in javascript, unfortunately img cannot returned, , needs displayed right afterwards? there seems no way arbitrarily display 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); } }; }
okay, trying seems impossible or @ least not easy in javascript reference:
ty
Comments
Post a Comment