fabricjs对象在组中的顺序 [英] fabricjs objects order in group

查看:301
本文介绍了fabricjs对象在组中的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have no idea how to order objects in group other then repeat add and remove to sort the objects.

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

I tried unshift on group objects but it does not save state.

$(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)'
    }));
});

模板JSFiddle

推荐答案

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

You can use fabric.Object.prototype.moveTo(). There is an undocumented behavior: if the object you call it upon is a part of a group, the object is moved within the group's _objects array, effectively changing its z-index when the group is redrawn.

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

Also, make sure to somehow force fabric to redraw the group after that, e.g. set 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>

这篇关于fabricjs对象在组中的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆