fabricjs对象在组中的顺序

时间:2019-01-08 13:43:29

标签: javascript html canvas fabricjs

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

我在组对象上尝试过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

1 个答案:

答案 0 :(得分:1)

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

此外,请确保在此之后以某种方式强制面料重新绘制组。设置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>