Chapter 5. Animations, Part One

At some point in your career as a Raphaelite, you will probably discover that, like the Greek sculptor Pygmalion, you are so enamored with your creation that you wish it could become a living being. Pygmalion had to invoke the help of Venus. We only need to use animations.

We already have plenty of practice changing the properties of our objects, whether it’s altering their color or applying a transformation when the user clicks them. Animations do not introduce any fundamentally new concepts; they merely instruct Raphael to take its time getting from A to B.

The Basics

First, let’s dial up our pal the red dot.

var paper = Raphael(0, 0, 500, 500);
var dot = paper.circle(50, 50, 20).attr({ "fill": "red" });

Next, we’ll instantiate a new animation, which takes two arguments (for now): an object representing a series of properties we would like our element to have at the end of its journey, and the number of milliseconds it should take to reach this state.

var anim = Raphael.animation({ cx: 100, cy: 200, fill: "blue" }, 1000);

Note that dot is not referenced anywhere here. Like functions that can manipulate a wide variety of objects, animations exist independently of elements. We could apply this new animation to anything we like, though it won’t make much sense for elements that do not have a cx or cy property.

To connect the two, we feed anim to the .animate() method of our dot:

dot.animate(anim);

See this code live on jsFiddle.

Fire this up and you will see ...

Get RaphaelJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.