Search code examples
javascripthtmlcanvaskineticjs

Kinetic JS: Can I add multiple names to shapes?


I have the following for example to create a polygon:

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

What I would like to do is have two class names, for example "rect-1" and "rect-2". I want some of the shapes to have one of those classes, some will have both.

The point of this would be to be able to use the get() syntax to transition some shapes in one way, opacity for example, and other shapes in another way, offset for example:

Is it possible to gives shapes multiple "class" names for advanced selection as I described here?

Thanks!

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

Solution

  • This object filtering is not built-in yet, but one easy implementation could be to iterate through the stage children with the getChildren() method and test a conditional in this loop like

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

    Another solution with mono inheritance could be to subclass the Kinetic.Rect class using the extend() method and overload the shapeType attribute, which will become the key for your filtering.