简体   繁体   中英

How to remove overlay image from Fabric.js canvas?

I use overlay image on my Fabric.js and it is added like this:

canvas.setOverlayImage('image.png', canvas.renderAll.bind(canvas));

My problem is that I can't find to method to remove it from canvas. To remove objects I can use remove(object) from class fabric.StaticCanvas , but I haven't found a way how to serve overlay image as object to this method. I have tries to set overlay image to null :

canvas.setOverlayImage(null, canvas.renderAll.bind(canvas));

but it didn't help.

Looking at the source code, it almost looks like a bug that you can't set it to null in the way you'd expect (as a parameter to setOverlayImage). Looking at static_canvas.class.js you see the source code for setOverlayImage() :

setOverlayImage: function (url, callback) { // TODO (kangax): test callback
  return fabric.util.loadImage(url, function(img) {
    this.overlayImage = img;
    callback && callback();
  }, this);
}

And in util/misc.js you see the source code for util.loadImage() :

function loadImage(url, callback, context) {
  if (url) {
    var img = new Image();
    /** @ignore */
    img.onload = function () { 
      callback && callback.call(context, img);
      img = img.onload = null;
    };
    img.src = url;
  }
}

So you can see if you pass null to setOverlayImage() , null will in turn be the argument to util.loadImage() . And if the argument to the latter is null, the method does nothing, so in turn the whole operation does nothing.

It looks like you have to cheat and directly set the property on the canvas object:

canvas.overlayImage = null;
canvas.renderAll.bind(canvas);

I created a toggle that alternates between having an overlay image and a null overlay. This is possible after Kangax's update to the code:

function toggleOverlay(){
    if(!canvas.overlayImage){
        canvas.setOverlayImage(
            'img/transparent-overlay.png', 
            canvas.renderAll.bind(canvas)
        );
    }else{
        canvas.setOverlayImage(null, canvas.renderAll.bind(canvas));
    }
}

代替Null只是将其留空。

canvas.setOverlayImage('', canvas.renderAll.bind(canvas));

I have found the same issue
I fixed by setting backgroundImage = 0

self.canvas.backgroundImage = 0;

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