fabricjs 对象按组排序

fabricjs objects order in group

我不知道如何对组中的对象进行排序,然后重复添加和删除以对对象进行排序。

我在组对象上尝试了 unshift,但它不保存状态。

$(document).on("click", "#addToGroup", function() { 
var objects = canvas.getActiveObject();

    if(objects && objects.type === "activeSelection") {
      objects.toGroup();
      canvas.requestRenderAll();
    }   
});


count = 1;   

$(document).on("click", "#addObject", function() {
    canvas.add(new fabric.Rect({
      width: 100, height: 100, left: 100 + (count * 20), top: 20 + (count * 10), angle: -10,
      fill: 'rgba(0,200,0,1)'
    }));
});

Template JSFiddle

您可以使用 fabric.Object.prototype.moveTo()。有一个未记录的行为:如果您调用它的对象是组的一部分,则该对象会在组的 _objects 数组中移动,从而在重绘组时有效地更改其 z-index。

此外,确保以某种方式强制 fabric 在之后重新绘制组,例如设置 group.dirty = true.

const canvas = new fabric.Canvas("c")

const a = new fabric.Rect({
  width: 100,
  height: 100,
  left: 100,
  top: 20,
  angle: -10,
  fill: 'rgba(0,200,0,1)'
})
const b = new fabric.Rect({
  width: 50,
  height: 100,
  left: 150,
  top: 50,
  angle: 45,
  stroke: '#eee',
  strokeWidth: 10,
  fill: 'rgba(0,0,200,1)'
})
const c = new fabric.Circle({
  radius: 50,
  left: 150,
  top: 75,
  fill: '#aac'
})

const group = new fabric.Group([a, b, c])
canvas.add(group).requestRenderAll()

document.querySelector('#b1').addEventListener('click', () => {
  const bottomChild = group.getObjects()[0]
  bottomChild.moveTo(group.size() - 1)
  // force fabric to redraw the group
  group.dirty = true
  canvas.requestRenderAll()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.js"></script>
<canvas id='c' width="400" height="200"></canvas>
<button id='b1'>move bottom to top</button>