Creating and selecting a group programmatically with Fabric.js

放肆的年华 提交于 2019-12-09 13:30:22

问题


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.

Is that possible?

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();

回答1:


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

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




回答2:


Adding the selected items as group produced weird results when redrawing connections to them afterwards for me. fabic's ActiveSelection is the intended Group Object for programatically adding a Selection Group to Canvas now (probably didn't exist in 2013)

Here's my snipped that also works with following move events, it's selecting items based on two attributes 'issueType' and 'clusterIndex':

let allObjects = CANVAS.getObjects();
let selectedObjects = [];
for(let i=0;i < allObjects.length;i++){
    let object = allObjects[i];
    if(object.issueType && object.clusterIndex === clusterIndex){
        selectedObjects.push(object);
        }
    }
let selectionGroup = new fabric.ActiveSelection(selectedObjects);
CANVAS.add(selectionGroup);
CANVAS.setActiveObject(selectionGroup);



回答3:


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

the above code should would work for you it will anyway group objects 1,2,3

all you have to do is to get rid of the original objects and group the clones



来源:https://stackoverflow.com/questions/19632006/creating-and-selecting-a-group-programmatically-with-fabric-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!