选择下一个/上一个项目并将其放在Fabric js中

时间:2018-07-24 15:00:51

标签: vue.js fabricjs

想象一下,我们在画布上有10个项目。我需要实现nextprevious按钮。

当我单击下一步时,如果有活动对象,则应选择下一个对象并将其放在最前面,以便用户可以轻松地单击该项目并将其移动。

但是在fabricJs中,所有层都表示为对象数组。当我将对象放在最前面时,它会更改其索引。例如,我们有3个项目:

1 // currently selected
2 
3

然后,我将2项设置为活动状态并将其置于前面。数组现在变为:

2 // currently selected and brought to top
1
3

然后,如果我选择下一项,它将是1,而不是3。

这是示例代码:

selectNextItem() {
  let activeObject = this.canvas.getActiveObject()

  if (!activeObject) {
    return false
  }

  let totalObjectsNumber = this.canvas.getObjects().length
  let currentIndex = this.canvas.getObjects().indexOf(activeObject)
  let nextIndex = null

  // We reached the last item, rewind to the beginning
  if (currentIndex === totalObjectsNumber - 1) {
    nextIndex = 0
  } else {
    nextIndex = currentIndex + 1
  }

  let object = this.canvas.item(nextIndex)
  this.canvas.setActiveObject(object)
  object.bringToFront() // <--- this causes problem

  this.canvas.renderAll()
}

因此,我了解出了什么问题,但无法找出解决方法。在任何图形编辑器中,如果我选择下一层,它都不会置顶。如果将其置于顶部,则无法继续此操作,并选择下一层并将其也置于顶部。

我将织物与vueJs结合使用。

1 个答案:

答案 0 :(得分:0)

我尝试使用您的函数,但使用Fabricjs 2.3.3对我来说效果很好。您使用什么版本?

 var canvas  = new fabric.Canvas('c');


 var rect = new fabric.Rect({
        left: 100,
        top: 100,
        fill:  "#FF0000",
        stroke: "#000",
        width: 100,
        height: 100,
        strokeWidth: 10  
    });
    
  var rect2 = new fabric.Rect({
    left: 150,
    top: 150,
    fill:  "#FF0FF0",
    stroke: "#AABBCC",
    width: 100,
    height: 100,
    strokeWidth: 10     
  }); 
  var rect3 = new fabric.Rect({
    left: 75,
    top: 75,
    fill:  "#CCCFF0",
    stroke: "#DDBBFF",
    width: 100,
    height: 100,
    strokeWidth: 10  
  });

canvas.add(rect,rect2,rect3);
console.log(canvas.getObjects());

setInterval(function(){
	selectNextItem();
},1500);

function selectNextItem() {
	console.log('Select NEXT Item');
  let activeObject = canvas.getActiveObject()

  if (!activeObject) {
    return false
  }

  let totalObjectsNumber = canvas.getObjects().length
  let currentIndex = canvas.getObjects().indexOf(activeObject)
  let nextIndex = null

  // We reached the last item, rewind to the beginning
  if (currentIndex === totalObjectsNumber - 1) {
    nextIndex = 0
  } else {
    nextIndex = currentIndex + 1
  }

  let object = canvas.item(nextIndex)
  canvas.setActiveObject(object)
  object.bringToFront() // <--- this causes problem
  canvas.renderAll()
}
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">

    <title>React Redux Webpack ToDo App</title>
</head>

<body>
  
  <canvas id="c" width="500" height="500"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.js"></script>
</body>
</html>

请选择一个对象并查看结果。请让我知道这是否是正确的行为。