我正在用JavaScript和Raphael库构建一种JavaScript地图。当点击对象时,我能够缩放它,但是我希望它可以动画化(比如慢慢地深入等)。有没有方法可以在不重复制造轮子的情况下实现这个目标?
我正在用JavaScript和Raphael库构建一种JavaScript地图。当点击对象时,我能够缩放它,但是我希望它可以动画化(比如慢慢地深入等)。有没有方法可以在不重复制造轮子的情况下实现这个目标?
SVG对象的视图框(viewbox)可以被动画化,没有任何理由不能这样做--Raphael只是默认没有提供这样的功能。不过,创建一个插件是相当简单的。例如:
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 );
}
var paper = Raphael( 0, 0, 640, 480 );
paper.animateViewBox( 100, 100, 320, 240, 5000, '<>', function()
{
alert("View box updated! What's next?" );
} );
演示在这里展示。
Raphael动画通过动画元素属性来工作。当您调用element.animate时,您提供最终对象参数、到达时间以及可能的缓动函数(如果您不希望它是线性的)。
例如,要缩放圆形,您可以考虑使用此示例:http://jsfiddle.net/eUfCg/
// Creates canvas 320 × 200 at 10, 50
var paper = Raphael(10, 50, 320, 200);
// Creates circle at x = 50, y = 40, with radius 10
var circle = paper.circle(50, 40, 10);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff");
var zoomed = false;
circle.click(function () {
if (zoomed) {
this.animate({ transform: "s1" }, 500);
zoomed = false;
} else {
this.animate({ transform: "s4" }, 500);
zoomed = true;
}
});
这段代码涉及到圆形的变换属性。如果要缩放地图,您应该将所有元素放在一个组内,并动画化组的变换属性,考虑您想要达到的比例和平移。
有关变换属性的更多信息,请参见http://raphaeljs.com/reference.html#Element.transform。