0

Example here: http://jsfiddle.net/dhREK/32/

With Raphael JS I'm creating a series of triangles using a for loop. After creating the triangles I want to be able to animate any one of them by selecting the raphael objects by index, something like:

tri[1]

or

tri.1

but I'm not sure of the right syntax. In any case, using

tri.animate({fill: '#ff0000'}, 400)

only animates the last triangle.

How can I specifically select the other nodes?

Thanks!

var paper = new Raphael(0, 0, 500, 500);

for(var i = 0; i < 6; i++) {
    var coords = 'M 43 0 L 74 63 L 13 63 Z';

    if(i % 2) {
        coords = 'M 43 63 L 74 0 L 13 0 Z';                      
    }

    var tri = paper.path(coords).attr({
       'fill' : '#000',
        'stroke-width' : '0'
    });

    tri.transform('T'+i * 34+',0');
}


tri.animate({fill: '#ff0000'}, 400)

PS: I was able to get all of the children of my paper as jquery objects (as seen in the jsfiddle link), but using animate() on a jquery object does not allow me to animate the raphael properties... any comment on that would be much appreciated as well!

2 Answers 2

4

More appropriate for this situation would be an array-like Paper.set

You can define it like this

var triangles = Paper.set();

for(var i = 0; i < 6; i++) {
  // ....
  var tri = paper.path(coords) //

  triangles.push(tri);
}

triangles.animate(
  // ...
);
2
  • Once they are in the set, how would I select individual triangles by index? Aug 6, 2012 at 15:26
  • @j-man86 Like a normal array, e.g. triangles[1]. The advantage is that it implements the composite pattern, meaning you can use for example Element.animate on a whole set.
    – dan-lee
    Aug 6, 2012 at 15:33
1

Turn tri into an array.

var paper = new Raphael(0, 0, 500, 500),
    tri = [];

for(var i = 0; i < 6; i++) {
    var coords = 'M 43 0 L 74 63 L 13 63 Z';

    if(i % 2) {
        coords = 'M 43 63 L 74 0 L 13 0 Z';                      
    }

    tri[i] = paper.path(coords).attr({
       'fill' : '#000',
        'stroke-width' : '0'
    });

    tri[i].transform('T'+i * 34+',0');
}


tri[1].animate({fill: '#ff0000'}, 400);
2
  • I strongly suggest implementing Paper.set instead of array in accordance with Dan Lees answer.
    – bennedich
    Aug 6, 2012 at 16:42
  • I also strongly recommend implementing Paper.set rather than an array. Aug 6, 2012 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.