简体   繁体   中英

Detect whether Image is broken in Javascript

I'm adding images to an HTML5 canvas using Javascript:

img = new Image(); 
img.addEventListener('load', loadCallBack, false);
img.src = image_url;

And then loadCallBack draws the image.

The problem is that sometimes the image_url refers to a broken or nonexistent image. When this happens, I get a 404 error in the console and the image on the canvas stays white. Instead, I'd like to be able to replace the image's src attribute with another image_url .

I tried the following and it did not work:

img.addEventListener("error", function(){console.log("404");});

How can I detect the 404s of the images?

Note: I'm still looking for a solution, as neither of the two posted so far has worked.

The same code as the Kostia's answer: just to compare the ugliness of jQuery and the beauty of vanilla javascript:

function brokenImage() { ... }

img = new Image();
img.onerror = brokenImage;
img.src = "invalid_img_name.png";​

Works in jQuery for me... http://jsfiddle.net/5v2qG/

img = new Image(); 
$(img).bind('error', function () {
      alert('error called');                                                
});
img.src = "invalid_img_name.png";​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM