使用 Fabric.js 选择画布上的所有对象

2022-01-17 00:00:00 javascript html5-canvas fabricjs

有没有办法显式选择在特定时间实例中存在的所有对象.这可以很容易地使用鼠标选择所有.是否有一个代码解决方案,例如一个名为 Select All 的按钮,以便单击它会使所有织物类型对象都被选中,然后我可以使用 canvas 将更改应用于整个 ActiveGroup.getActiveGroup(); 并迭代.

Is there a way to explicitly select all the objects present at a particular instance of time. This can be easily done using mouse to select all. Is there a code-solution like a button named Select All so that clicking it would make all the fabric type objects being selected and then I could apply the changes to whole of that ActiveGroup using canvas.getActiveGroup(); and iterate over.

推荐答案

好问题.

对此没有内置方法,但您需要按照以下方式进行操作:

There's no built-in method for this, but you would need to do something along these lines:

var objs = canvas.getObjects().map(function(o) {
  return o.set('active', true);
});

var group = new fabric.Group(objs, {
  originX: 'center', 
  originY: 'center'
});

canvas._activeObject = null;

canvas.setActiveGroup(group.setCoords()).renderAll();

代码应该是不言自明的,当您使用鼠标、shift+click 等时,它几乎就是幕后发生的事情.

The code should be self-explanatory, and it's pretty much what's happening under the hood when you use mouse, shift+click, etc.

相关文章