[英]Detect whether Image is broken in Javascript
I'm adding images to an HTML5 canvas using Javascript: 我正在使用Javascript将图像添加到HTML5画布:
img = new Image();
img.addEventListener('load', loadCallBack, false);
img.src = image_url;
And then loadCallBack
draws the image. 然后
loadCallBack
绘制图像。
The problem is that sometimes the image_url
refers to a broken or nonexistent image. 问题是有时
image_url
指的是破损或不存在的图像。 When this happens, I get a 404 error in the console and the image on the canvas stays white. 发生这种情况时,我在控制台中出现404错误,并且画布上的图像保持白色。 Instead, I'd like to be able to replace the image's
src
attribute with another image_url
. 相反,我希望能够将图像的
src
属性替换为另一个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? 如何检测图像的404?
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: 与Kostia的答案相同的代码:只是为了比较jQuery的丑陋和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/ 在我的jQuery工作... http://jsfiddle.net/5v2qG/
img = new Image();
$(img).bind('error', function () {
alert('error called');
});
img.src = "invalid_img_name.png";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.