我建議使用矢量(SVG)庫,即raphael.js爲動畫部分。
在raphael.js中,您可以定義路徑,然後沿着該路徑的長度爲任何對象設置動畫效果。
請看例子,以便更好地理解相應的計算器線程:
相比線程,你需要在附加動畫onScroll事件,而不是將其附加到間隔。
編輯:
添加從link相關的代碼片段,作爲評論者建議:
HTML:
<div id="holder"></div>
JS:
var e;
var myPath;
var animation; //make the variables global, so you can access them in the animation function
window.onload = function() {
var r = Raphael("holder", 620, 420),
discattr = {
fill: "#666",
stroke: "none"
};
function curve(x, y, zx, zy, colour) {
var ax = Math.floor(Math.random() * 200) + x;
var ay = Math.floor(Math.random() * 200) + (y - 100);
var bx = Math.floor(Math.random() * 200) + (zx - 200);
var by = Math.floor(Math.random() * 200) + (zy - 100);
e = r.image("http://openclipart.org/image/800px/svg_to_png/10310/Odysseus_boy.png", x, y, 10, 10);
var path = [["M", x, y], ["C", ax, ay, bx, by, zx, zy]];
myPath = r.path(path).attr({
stroke: colour,
"stroke-width": 2,
"stroke-linecap": "round",
"stroke-opacity": 0.2
});
controls = r.set(
r.circle(x, y, 5).attr(discattr), r.circle(zx, zy, 5).attr(discattr));
}
curve(100,100,200,300,"red");
animation = window.setInterval("animate()", 10); //execute the animation function all 10ms (change the value for another speed)
};
var counter = 0; // a counter that counts animation steps
function animate(){
if(myPath.getTotalLength() <= counter){ //break as soon as the total length is reached
clearInterval(animation);
return;
}
var pos = myPath.getPointAtLength(counter); //get the position (see Raphael docs)
e.attr({x: pos.x, y: pos.y}); //set the circle position
counter++; // count the step counter one up
};
更新:
我最近用pathAnimator來完成同樣的任務。小心演出,但複雜的動畫可能會相當密集。
請考慮在此處鏈接發佈相關內容。如果將來鏈路不可用,答案將變得無關緊要。 – War10ck
很好的答案,夫婦的建議。讓這種「順利」(如@Isis所要求的)的一種方法是減輕向最終位置的移動。 1:使用'requestAnimationFrame'代替最大平滑度的間隔。 2:像這樣計算緩動:'x + =(pos.x - x)* 0.2'(更改0.2以滿足您的緩解需求) – potench