raphael viewbox动画缩放

Alm*_*bin 3 javascript svg raphael

我用javascript和Raphael lib构建了一种javascript地图.点击时我可以放大一个物体,但是我希望它能够被动画化(比如慢慢潜入等等).有没有办法这样做而不重新发明轮子?

Kev*_*sen 6

没有理由不能动画svg对象的视图框 - 拉斐尔根本不提供开箱即用的功能.但是,创建插件相当简单.例如:

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 );
}
Run Code Online (Sandbox Code Playgroud)

安装此插件后实例化的任何纸张都可以使用animateViewBox,方法与Raphael的内置动画方法完全相同.例如...

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

演示在这里上演.