Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image.fromURL error callback

Tags:

fabricjs

I am trying to load an image using the fromURL. The issue is that I'd like it to be able to load a default icon if it is not able to reach the Image server to download the image. Looking at the docs I did not see an error callback for the fromURL function. How are we supposed to catch that the call was not successful and therefore do the appropriate thing? It does not seem that the callback gets called at all when image load was unsuccessful.

like image 901
Alexander Ventura Avatar asked May 09 '14 20:05

Alexander Ventura


3 Answers

You can use fabric.util.loadImage() method instead of fabric.Image.fromURL().

If you look at the fromURL() method implementation, internally it uses the loadImage().

The following code may help you:

fabric.util.loadImage('https://s3-eu-west-1.amazonaws.com/kienzle.dev.cors/img/image2.png', function(img) {
    if(img == null) {
        alert("Error!");
    }else {
        var image = new fabric.Image(img);
        canvas.add(image).setActiveObject(image);
        canvas.renderAll();
    }
}, { crossOrigin: 'anonymous' });

Here is the fiddle: http://jsfiddle.net/k7moorthi/30kmn5kL/

like image 82
Kesavamoorthi Avatar answered Jan 03 '23 12:01

Kesavamoorthi


once you have done the function, even if theres a mistake the callback keeps running, then you could check for the element (as other said) in this way:

let fabricBackgroundInstance = new fabric.Image.fromURL(imageToUse, (oImg) => {

  if(oImg._element == null){
    console.error('oImg', oImg._element);
    return;
  }
like image 28
jmchema Avatar answered Jan 03 '23 13:01

jmchema


You could use getElement() to check this error.

fabric.Image.fromURL('/foo.jpg', (img) => {
  if (img.getElement() === undefined) {
    console.log('Failed to load image!');
    return;
  }
  // do something on success
}
like image 43
Devin Chen Avatar answered Jan 03 '23 12:01

Devin Chen