raphael viewbox animated zoom

javascript, raphael, svg

Solution

There is no reason that the viewbox of an svg object cannot be animated -- Raphael simply doesn't provide such functionality out of the box. Creating a plugin is reasonably straightforward, however. For instance:

Raphael.fn.animateViewBox = function animateViewBox( x, y, w, h, duration, easing_function, callback )
{
    var cx = this._viewBox ? this._viewBox[0] : 0,
        dx = x - cx,
        cy = this._viewBox ? this._viewBox[1] : 0,
        dy = y - cy,
        cw = this._viewBox ? this._viewBox[2] : this.width,
        dw = w - cw,
        ch = this._viewBox ? this._viewBox[3] : this.height,
        dh = h - ch,
        self = this;;
    easing_function = easing_function || "linear";

    var interval = 25;
    var steps = duration / interval;
    var current_step = 0;
    var easing_formula = Raphael.easing_formulas[easing_function];

    var intervalID = setInterval( function()
        {
            var ratio = current_step / steps;
            self.setViewBox( cx + dx * easing_formula( ratio ),
                             cy + dy * easing_formula( ratio ),
                             cw + dw * easing_formula( ratio ),
                             ch + dh * easing_formula( ratio ), false );
            if ( current_step++ >= steps )
            {
                clearInterval( intervalID );
                callback && callback();
            }
        }, interval );
}

Any paper instantiated after this plugin is installed can use animateViewBox in exactly the same method Raphael's built-in animate method works. For instance...

var paper = Raphael( 0, 0, 640, 480 );
paper.animateViewBox( 100, 100, 320, 240, 5000, '<>', function()
    {
        alert("View box updated!  What's next?" );
    } );

Demonstration staged here.

Problem

I'm build a kind of javascript map with javascript and the Raphael lib. I'm able to zoom on an object when clicked, but I want it to be animated (like slowly diving in and so on). Is there a way to do so without reinventing the wheel?

Original source

Related problems