HandiworkNYC.com
HandiworkNYC.com

Reputation: 11114

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

Upvotes: 0

Views: 1478

Answers (3)

Matt Slocum
Matt Slocum

Reputation: 350

The Kinetic function is publicly accessible, so you can easily overwrite it with your own version. Here's how I fixed it.

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

Eric, if you like it, feel free to add it to Kinetic. I might submit a pull request soon.

Upvotes: 0

Eric Rowell
Eric Rowell

Reputation: 5219

Interesting use case! I'll add this to my todo list. perhaps something like this:

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

would assign three different names (similar to DOM class name strings)

Upvotes: 8

Delapouite
Delapouite

Reputation: 10187

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.

Upvotes: 3

Related Questions