Control z-index in Fabric.js

后端 未结 5 1123
独厮守ぢ
独厮守ぢ 2021-02-05 05:35

In fabricjs, I want to create a scene in which the object under the mouse rises to the top of the scene in z-index, then once the mouse leaves that object, it goes back to the z

相关标签:
5条回答
  • 2021-02-05 05:47

    After I added a line object, I was make the line appear under the object using:

    canvas.add(line);
    canvas.sendToBack(line);
    

    Other options are

    • canvas.sendBackwards
    • canvas.sendToBack
    • canvas.bringForward
    • canvas.bringToFront

    see: https://github.com/fabricjs/fabric.js/issues/135

    0 讨论(0)
  • 2021-02-05 05:50

    You can modify your _chooseObjectsToRender method to have the following change at the end of it, and you'll be able to achieve css-style zIndexing.

    objsToRender = objsToRender.sort(function(a, b) {
      var sortValue = 0, az = a.zIndex || 0, bz = b.zIndex || 0;
    
      if (az < bz) {
        sortValue = -1;
      }
      else if (az > bz) {
        sortValue = 1;
      }
    
      return sortValue;
    });
    

    https://github.com/fabricjs/fabric.js/pull/5088/files

    0 讨论(0)
  • 2021-02-05 05:51

    Also make sure you change z-index AFTER adding object to canvas.

    So code will looks like:

    canvas.add(object);
    canvas.moveTo(object, index);
    

    Otherwise fabricjs don`t care about z-indexes you setup.

    0 讨论(0)
  • 2021-02-05 06:07

    You can use these two functions to get z-index of a fabric object and modify an object's z-index, since there is not specific method to modify z-index by object index :

    fabric.Object.prototype.getZIndex = function() {
        return this.canvas.getObjects().indexOf(this);
    }
    
    fabric.Canvas.prototype.moveToLayer = function(object,position) {
        while(object.getZIndex() > position) {
            this.sendBackwards(object);
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:13

    Since fabric.js version 1.1.4 a new method for zIndex manipulation is available:

    canvas.moveTo(object, index);
    object.moveTo(index);
    

    I think this is helpful for your use case. I've updated your jsfiddle - i hope this is what you want:
    jsfiddle

    0 讨论(0)
提交回复
热议问题