2013-11-24 39 views
0

我試圖用畫布實現正弦波演示。我可以用動畫繪製正弦波。但我的問題是我想將畫布向左移動,因爲正弦波動畫超出了畫布的視口。這是我的代碼。如何水平向負x軸平移畫布

<canvas id='a' width="320" height="480"></canvas> 

的Javascript:

var rot=0; 
var c= document.getElementById('a'); 

function a(){ 
setInterval(function(){ 
    ctx=c.getContext('2d'); 
    ctx.fillStyle="red"; 
    rad=rot*Math.PI/180; 
    var x=100+100*Math.cos(rad); 
    var y=100+100*Math.sin(rad); 
    ctx.fillRect(rot,y,1,1); 
    rot++; 
},10); 
} 
a(); 
+0

也許[在畫布上製作和動畫波](http://stackoverflow.com/questions/19787775/make-and-animate-wave-in-canvas/19803396#19803396)可以提供幫助。 –

+0

謝謝Anto,但是MarkE給了我所需要的東西.. –

回答

1

演示: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); 
     } 
    } 
} 

當然,如果你有在畫布上繪製的其他資產,你也必須重繪他們(重繪與或沒有平移根據您的設計需要)。

+0

賓果遊戲!!!這就是我想要的。非常感謝兄弟。如果你在附近,我會給你買一瓶啤酒...;))) –

+0

如果你能告訴我哪裏可以得到基於三角學的畫布教程,那將是非常好的。 –

+0

好消息...所有的三角函數已經內置到JavaScript的「數學」方法。這意味着沒有適用於HTML畫布的「特殊」觸發器。因此,您發現的任何觸發教程(例如youTube)都將直接應用於HTML畫布。乾杯! – markE