Search code examples
javascripthtmlcanvaskineticjs

Kinetic.js Use a String to Search for ID


EDIT: I want to use a string rectString because I will be using a loop to get all the rectangles and checking to see if any of them have a specific property.

I have a set of rectangles, say their names are 'rect1' , 'rect2' , and 'rect3'. I have been trying to search different ways to search my stage such as:

var rectString="rect1";
var method1= stage.get(rectString)[0];
var method2= stage.get(rectString);
var method3 =stage.find(rectString);
var method4=node.getAttr(rectString);

and unfortunately none of these work. I am trying to get the stroke color of the shape and then change it using the ID of the shape. Thanks for your help


Solution

  • This will get all the rectangles on the stage into a collection:

    var allRectangles=stage.find("Rect");
    

    Then you can apply a function to each rectangle like this:

    // run a function for each element in the allRectangles collection
    
    allRectangles.each(function(rect){
    
        // check if this rect has a red stroke
    
        if(rect.stroke()=="red"){
    
            // if the stroke is red, change the stroke to blue
    
            rect.stroke("blue");
    
        }
    
    });
    
    layer.draw();