面料中心所有对象作为组

时间:2017-08-22 11:52:17

标签: javascript html5 html5-canvas fabricjs

我最近开始使用fabricjs,我对组有疑问。当画布调整大小时,我想将所有对象(许多)居中。所以我决定在我的画布中构建一个包含所有对象的组并将其居中。

然而,为了做到这一点,我必须:

  • 检索所有对象
  • 将它们添加到我的论坛
  • 从我的画布中删除它们
  • 将该组添加到我的画布

一个复杂的过程,最重要的是,我的对象失去了单独操作的可能性。

我想知道是否可以操作组而不在画布中添加它?

2 个答案:

答案 0 :(得分:0)

你需要这个小组吗?或者您只是创建它们以使对象居中?如果没有,您可以对要在屏幕中居中的每个画布对象使用object.center()

canvas.forEachObject(function (o) {
    o.center();
});

答案 1 :(得分:0)

此代码应与fabric 2.0 beta一起使用。 版本1.7.x也可以使用类似的代码,您可以使用activeGroup逻辑从中创建。

您可能想要做的是:

// After the canvas resize:
// get all Objects:
var objects = canvas.getObjects();
// create a multiselection
var selection = new fabric.ActiveSelection(objects, { canvas: canvas });
// now get size of this selection:
var width = selection.width;
var height = selection.height;
// scale the selection accordingly
var scale = ( find the right scale value, probably canvas.width/width or canvas.height/height. The biggest or smaller of them )
selection.scale(scale);
// center the selection in the canvas
selection.center();
// destroy the selection
selection.destroy();

这应该有效。

相关问题