Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raphael JS : how to move/animate a path object?

Somehow this doesn't work...

var paper = Raphael("test", 500, 500);

var testpath = paper.path('M100 100L190 190');

var a = paper.rect(0,0,10,10);
a.attr('fill', 'silver');

a.mousedown( function() {
  testpath.animate({x: 400}, 1000);
});

I can move rects this way but not paths, why is that, and how do I move a path object then?!

like image 738
Dylan Avatar asked Jun 08 '11 16:06

Dylan


4 Answers

With the latest version of Raphael, you can do this:

var _transformedPath = Raphael.transformPath('M100 100L190 190', 'T400,0');
testpath.animate({path: _transformedPath}, 1000);

This saves you from the trouble of having to clone a temp object.

like image 119
TimDog Avatar answered Oct 21 '22 14:10

TimDog


It seems a path object doesn't get a x,y value - so your animation probably still runs, but does nothing. Try instead animating the path function:

testpath.animate({path:'M400 100L490 190'},1000);

It makes it a bit trickier to write the animation, but you have the benefit of getting rotation and scaling for free!

BTW: I'm sure this is just an example, but in your above code testpath gets put in the global scope because you don't initialize as var testpath

like image 18
Rudu Avatar answered Oct 21 '22 14:10

Rudu


Solved, with thanx to Rudu!

You need to create a new path to animate to. You can do this with clone() and then apply the transformations to that clone. Seems very complex for a simple move like this, but it works...

var paper = Raphael("test", 500, 500);

var testpath = paper.path('M100 100L190 190');

var a = paper.rect(0,0,10,10);
a.attr('fill', 'silver');

a.mousedown( function() {

  var temp = testpath.clone();
  temp.translate(400,0);
  testpath.animate({path: temp.attr('path')}, 1000);
  temp.remove();

});
like image 10
Dylan Avatar answered Oct 21 '22 13:10

Dylan


TimDog answer was best solution.

In addition, just remember, transform string in this case means, that it will add 400 points to every path point/line X coordinate, and 0 points to every Y coordinate.

That means, M100 100L190 190 will turn into M500 100L590 190.

So, if you need to move a path element to another position, the difference between current position and new position coordinates should be calculated. You can use first element to do that:

var newCoordinates = [300, 200],
curPos = testpath.path[0],
newPosX = newCoordinates[0] - curPos[1],
newPosY = newCoordinates[1] - curPos[2];

var _transformedPath = Raphael.transformPath(testpath.path, "T"+newPosX+","+newPosY);
testpath.animate({path: _transformedPath});

Hope this will help someone.

like image 4
Deele Avatar answered Oct 21 '22 15:10

Deele