Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Looping Animation with JavaScript and Raphaël

DZone's Guide to

Looping Animation with JavaScript and Raphaël

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

Raphael is a popular JavaScript library helping you to manage vectors via SVG or VML in your browser. It is extremely helpful and very easy to learn and use. The interesting thing is that in the browser you can do very powerful things with vectors, but they remain very less known. However with such libraries like Raphael the task is really simple.

Animation

As I said animating some vector properties is as simple as:

var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});
c.animate({r : 10, fill : '#00f'}, 1000);

Here we change the radius and the background color of the circle for 1000 milliseconds.

The same thing can be done with any property with any other JavaScript library as jQuery. But as in jQuery, Raphael or whatever library the animation is not looping. That’s natural you can just change a property by animating it, but the looping animation suggests at least two animations. So it’s a developers job to implement this. Here’s a simple way to do this.

Two Way Animation

The solution here is using two functions calling each other.

var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});

function a() {
c.animate({r : 10, fill : '#00f'}, 1000, b);
}
function b() {
c.animate({r : 6, fill : '#f00'}, 1000, a);
}
a();

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}