【问题标题】:fabricjs objects order in group组中的fabricjs对象顺序
【发布时间】:2019-01-09 01:29:24
【问题描述】:

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

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

【问题讨论】:

标签: javascript html canvas fabricjs


【解决方案1】:

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

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

【讨论】:

  • 不错,结合 'addWithUpdate' 和 'moveTo' 可以在不删除的情况下进行订购。
猜你喜欢
  • 1970-01-01
  • 2015-10-12
  • 2016-03-06
  • 2021-06-11
  • 2020-04-09
  • 2017-09-27
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多