在 paperJS 中将自定义对象添加到组

Adding custom object to Group in paperJS

在 PaperJS 中,似乎只能将常规类型添加到组中。每当我尝试使用自定义对象附加组时,我都会收到错误 item._remove is not a function

每当我创建自己的对象时,例如:

function textBox(point, width) {
    this.box = new Path.Rectangle({
        point: point,
        size: new Size(width,40),
        strokeColor: new Color(0,0,0,0.1),
        fillColor: 'white',
        strokeWidth: 1
    });

    this.box.onMouseUp = function(event) {
        cursor = this.point + new Point(5,2);
    }

}

并尝试将其附加到组中:

var testGroup = new Group();
testGroup.appendTop(new textBox(new Point(0,0), 400));

出现错误。因此,我的问题是:如何将自定义对象添加到组中?当然,我不能期望在不使用组动态的情况下手动创建每个单独的对象或以其他方式在单独的级别上操纵它们。看起来我必须,就像 PaperJS 中的所有其他类型一样,让我的对象扩展 Item,但到目前为止我还没有让它接受我的构造函数。我想知道它需要什么才能被接受。

事实上,除了将它们与库一起编译之外,目前没有 built-in 机制来扩展 Paper.js 类。
因此,对于您似乎遇到的这种简单情况,我会使用一个工厂函数来实例化我的自定义对象,然后像与任何其他 Paper.js 对象一样与其交互。
例如,如果您的自定义对象是一个包含文本的框,您可以实例化一个包含矩形和文本的组,然后只与该组交互。

这里是 sketch 演示解决方案。

function createMyTextBox(point, content) {
    // Create a text item
    var text = new PointText({
        point: point,
        content: content,
        fontSize: 36,
        fillColor: 'red',
        justification: 'center'
    });

    // Create a rectangle around the text
    var rectangle = new Path.Rectangle({
        rectangle: text.bounds.scale(1.2),
        strokeColor: 'black'
    });

    // Create a Group that will wrap our items.
    var group = new Group([text, rectangle]);

    // Return the group
    return group;
}

// Create 2 text boxes
var textBox1 = createMyTextBox(view.center, 'text 1');
var textBox2 = createMyTextBox(view.center + [0, 100], 'text 2');

// You can use text boxes like regular items.
textBox2.translate(100, 0);
textBox2.scale(0.8);