Search code examples
kineticjs

Does kineticjs provide attribute Selector?


Does kineticjs provide attributeSelector?

I have a number of Kinetic shapes which contains same name. Some of the shapes contain a custom attribute suppose "userType". Can I filter based on "useType" from the given shapes using kineticjs instead of doing it manually?


Solution

  • KineticJS has a myContainer.getChildren(fn) method that lets you specify a function used to fetch a collection of children from a container.

    For example, if you have added these Circle objects to the layer:

    // add 3 Circles with attribute 'userType==pickMe!'
    
    for(var i=0;i<3;i++){
        var c=new Kinetic.Circle({id:i,x:50,y:50+i*40,radius:15,fill:"red"});
        c.setAttr('userType','pickMe!');
        layer.add(c);
    }
    
    // add 1 circle with attribute 'userType==dontPickMe.'
    
    var c=new Kinetic.Circle({id:i,x:50,y:170,radius:15,fill:"blue"});
    c.setAttr('userType','dontPickMe.');
    layer.add(c);
    

    Then you can use layer.getChildren to fetch the elements with 'userType==pickMe!'

    // `var found` will contain the 3 Circles with 'userType==pickMe!'
    
    var found=layer.getChildren(function(node){
        return(node.getAttr('userType')=='pickMe!');
    });