js以编程方式创建和选择组

js以编程方式创建和选择组

本文介绍了使用Fabric.js以编程方式创建和选择组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含6个对象的画布和一个位于画布外部的按钮.

Let's say I have a canvas containing 6 objects and a button outside of canvas.

当我单击此按钮时,其中三个对象将成为一个组并被选中,这些对象将保持其相对于画布的位置.

When I click this button, 3 of this objects will to become a group and selected, objects will keep their positions relative to canvas.

有可能吗?

我尝试了很多事情,但可以设法解决.我正在寻找的解决方案如下所示.

I tried so many things but could manage it to work. The solution that I'm looking for is something like below.

var objectList=[1,2,3];
var newgroup = new fabric.Group();

$.each(objectList, function (i) {
    var obj = canvas.item(i);
    newgroup.add(obj.clone());
    canvas.remove(obj);
});

canvas.add(newgroup)
canvas.setActiveGroup(newgroup);
canvas.renderAll();

推荐答案

您可以使用类似的方法:

You can use something like that:

(function() {
  var objectList = [1,2,3],
      group = new fabric.Group();

  canvas.forEachObject(function(o, i) {
    if (objectList.indexOf(i) > -1) {
      group.addWithUpdate(o);
      canvas.remove(o);
    }
  });
  canvas.setActiveObject(group);
  canvas.add(group);
})();

只有索引1、2或3的对象才添加到组中.

Only the objects at index 1, 2 or 3 are added to group.

这篇关于使用Fabric.js以编程方式创建和选择组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:53