演示:http://jsfiddle.net/m1erickson/K6SL3/
這裏的畫基礎上,正弦波的有效途徑X座標:
ctx.fillRect(x,Math.sin(x/10)*30+50,1,1);
直到波到達畫布的結尾,正常畫波
當波達到畫布的末端時,可以重新繪製整個波形,但向左移動1個像素。
// start panning when x reaches panAtX
var n1=x-panAtX;
// set up a temporary xx that draws the wave from -1 to the panAtX position
var xx=-1;
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// redraw the wave, but shifted 1 pixel to the left
for(n=n1;n<x;n++){
ctx.fillRect(xx++,Math.sin(n/10)*30+50,1,1);
}
所以把他們放在一起,你的動畫可能是這樣的:
var x=0;
var panAtX=250;
var continueAnimation=true;
animate();
function animate(){
if(continueAnimation){
requestAnimationFrame(animate);
}
if(x++<panAtX){
ctx.fillRect(x,Math.sin(x/10)*30+50,1,1);
}else{
var n1=x-panAtX;
var xx=-1;
ctx.clearRect(0,0,canvas.width,canvas.height);
for(n=n1;n<x;n++){
ctx.fillRect(xx++,Math.sin(n/10)*30+50,1,1);
}
}
}
當然,如果你有在畫布上繪製的其他資產,你也必須重繪他們(重繪與或沒有平移根據您的設計需要)。
也許[在畫布上製作和動畫波](http://stackoverflow.com/questions/19787775/make-and-animate-wave-in-canvas/19803396#19803396)可以提供幫助。 –
謝謝Anto,但是MarkE給了我所需要的東西.. –