我已经编写了一些 Javascript 代码来加载图像(由最终用户上传),如下所示:
var img = new Image;
var ctx = _this.canvas.getContext('2d');
img.onload = function(){
ctx.drawImage(img, 0, 0, img.width, img.height);
//do other stuff..
}
img.onerror = function(event){
bootbox.alert("Error loading the image!");
}
img.src = Settings.URL + '/images/loadimage/?imageKey=' + imageKey;
如果imageKey
对应的图片不存在,服务器返回404响应,其他错误场景也返回错误500。
这段代码工作正常,但我想做的是在以下两种不同的情况下显示两条不同的消息:
- 当我收到 404 响应时。
- 当错误 500 响应时。
我无法弄清楚的是 - 如何在 img.onerror
中获取响应代码。
最佳答案
onerror method不提供有关发生的错误类型的任何信息。引用this Stackoverflow post ,“image.onerror
处理程序将收到一个事件参数,该参数不包含有关错误原因的任何信息”。
In this blog post你会发现一些提示如何处理可能不存在的图像加载。在您的情况下,一个快速的解决方案是在您可以访问网络状态的地方使用 XMLHttpRequest 加载图像:
let imageReq = new XMLHttpRequest();
imageReq.open("GET", Settings.URL + '/images/loadimage/?imageKey=' + imageKey, true);
imageReq.responseType = "blob";
imageReq.onload = function(imageEvent) {
// the variable below will contain your image as BLOB data
var blob = imageReq.response;
let img = new Image;
let ctx = _this.canvas.getContext('2d');
img.onload = function() {
ctx.drawImage(img, 0, 0, img.width, img.height);
//do other stuff..
}
let urlCreator = window.URL || window.webkitURL;
let imageUrl = urlCreator.createObjectURL(blob);
img.src = imageUrl;
};
imageReq.onreadystatechange = function (imageEvent) {
if (imageReq.readyState === 4) {
if (imageReq.status === 200) {
// image has been loaded correctly
} else if (imageReq.status === 404) {
console.log("Image not found");
} else if (imageReq.status === 500) {
console.error("An error occurred:", imageReq.statusText);
}
}
};
imageReq.send(null);
关于javascript - 在 HTML Canvas 上加载图像时处理 Image.onerror 中的 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568665/