Kinetic JS:我可以在形状中添加多个名称吗?

Kinetic JS: Can I add multiple names to shapes?

本文关键字:添加 JS 我可以 Kinetic      更新时间:2023-09-26

例如,我有以下内容来创建多边形:

            var poly = new Kinetic.Polygon({
                x: coorx,
                y: coory,
                points: coords,
                alpha: 0,
                fill: colors[Math.floor(Math.random() * colors.length)],
                name: myname
            }); 

我想做的是有两个类名,例如"rect-1"和"rect-2"。我希望一些形状具有其中一个类,有些形状将同时具有这两个类。

这样做的目的是能够使用 get() 语法以一种方式转换某些形状,例如不透明度,以另一种方式转换其他形状,例如偏移量:

是否可以像我在这里描述的那样为形状提供多个"类"名称以进行高级选择?

谢谢!

    var shapes = stage.get(".rect-1");
    for(var n = 0; n < shapes.length; n++) {
        var shape = shapes[n];
        shape.transitionTo({
            alpha: (opacities[Math.floor(Math.random() * opacities.length)] * 1.5) + .7,
            duration: 2
        });                 
    }
    var shapes = stage.get(".rect-2");
    for(var n = 0; n < shapes.length; n++) {
        var shape = shapes[n];
        shape.transitionTo({
            offset: {
                x: 10,
                y: 10
            },
            duration: 2
        });                 
    }

有趣的用例! 我会把它添加到我的待办事项列表中。 也许是这样的:

var rect = new Kinetic.Rect({
   name: 'foo bar test'
});

将分配三个不同的名称(类似于 DOM 类名称字符串)

这个对象过滤还没有内置,但一个简单的实现可能是使用 getChildren() 方法遍历阶段子项,并在此循环中测试条件,例如

if shape.get('classList') && shape.get('classList').indexOf('rect1') !== -1

使用单声道继承的另一种解决方案可能是使用 extend() 方法对 Kinetic.Rect 类进行子类化,并重载 shapeType 属性,该属性将成为筛选的键。

Kinetic 函数是可公开访问的,因此您可以使用自己的版本轻松覆盖它。这是我修复它的方法。

Kinetic._addName = function(node, name) {
    if(name !== undefined) {
        var names = name.split(/'W+/g);
        for(var n = 0; n < names.length; n++) {
            if (names[n]) {
                if(this.names[names[n]] === undefined) {
                    this.names[names[n]] = [];
                }
                this.names[names[n]].push(node);
            }
        }
    }
};

埃里克,如果你喜欢它,请随时将其添加到Kinetic。我可能很快就会提交拉取请求。