Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling 404 inside Image.onerror when loading an image on HTML canvas

I have written some Javascript code to load an image (uploaded by the end user) which looks as follows :

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;

Server returns 404 response if the image corresponding to the imageKey does not exist, it also returns error 500 in other error scenarios.

This code works fine, but what I want to do is to show two different messages in the following two different cases:

  1. When I get 404 response.
  2. When Error 500 response.

What I am not able to figure out is - how to get response code in img.onerror.

like image 591
Tarun Gupta Avatar asked Nov 25 '25 04:11

Tarun Gupta


1 Answers

The onerror method does not provide any information about the kind of error that occurred. Referring to this Stackoverflow post, "the image.onerror handler will receive a single Event parameter that doesn't contain any info on the cause of the error".

In this blog post you'll find some hints how to handle loading of images that may not exist. A quick solution in your case would be to load the image(s) with XMLHttpRequest where you have access to the network status:

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);
like image 152
Spark Fountain Avatar answered Nov 26 '25 20:11

Spark Fountain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!