在Fabric.js中控制z-index

前端之家收集整理的这篇文章主要介绍了在Fabric.js中控制z-index前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在fabricjs中,我想创建一个场景,鼠标中的对象在z-index中上升到场景的顶部,然后一旦鼠标离开该对象,它将返回到z-index.一个不能设置object.zindex(这将是不错的).相反,我正在使用一个放置在旧位置的对象列表中的占位符对象,然后使用canvas.insertAt将旧对象放回到列表中的位置.但是这不行.

http://jsfiddle.net/rFSEV/的状态.

var canvasS = new fabric.Canvas('canvasS',{ renderOnAddition: false,hoverCursor: 'pointer',selection: false });
var bars = {}; //storage for bars (bar number indexed by group object)
var selectedBar = null; //selected bar (group object)
var placeholder = new fabric.Text("XXXXX",{ fontSize: 12 });

//pass null or a bar
function selectBar(bar) {
    if (selectedBar) {
        //remove the old topmost bar and put it back in the right zindex
        //PROBLEM: It doesn't go back; it stays at the same zindex
        selectedBar.remove();
        canvasS.insertAt(selectedBar,selectedBar.XZIndex,true);
        selectedBar = null;
        }
    if (bar) {
        //put a placeholder object ("XXX" for now) in the position
        //where the bar was,and put the bar in the top position
        //so it shows topmost
        selectedBar = bar;
        canvasS.insertAt(placeholder,true);
        canvasS.add(bar);
        canvasS.renderAll();
        }
    }

canvasS.on({
     'mouse:move': function(e) {
        //hook up dynamic zorder
        if (!e.target) return;
        if (bars[e.target])
            selectBar(e.target);
        else
            selectBar(null);
        },});

var objcount = canvasS.getObjects().length;

//create bars
for (var i = 0; i < 20; ++i) {
    var rect = new fabric.Rect({
      left: 0,top: 0,rx: 3,ry: 3,stroke: 'red',width: 200,height: 25
    });
    rect.setGradientFill({
      x1: 0,y1: 0,x2: 0,y2: rect.height,colorStops: {
        0: '#080',1: '#fff'
      }
    });    
    var text = new fabric.Text("Bar number " + (i+1),{
        fontSize: 12
    });
    var group = new fabric.Group([ rect,text ],{
      left: i + 101,top: i * 4 + 26
    });
    group.hasControls = group.hasBorders = false;

    //our properties (not part of fabric)
    group.XBar = rect;
    group.XZIndex = objcount++;

    canvasS.add(group);
    bars[group] = i;
    }
canvasS.renderAll();

解决方法

由于fabric.js版本1.1.4可以使用zIndex操作的新方法
canvas.moveTo(object,index);
object.moveTo(index);

我认为这对你的用例很有帮助.我更新了你的jsfiddle – 我希望这是你想要的:
jsfiddle

猜你在找的JavaScript相关文章