2017-01-11 40 views
1

我是新來的畫布,我想改變移動紅色矩形周圍的速度,因爲它目前正在慢慢移動(60fps),而且我也嘗試過setTimeout,但並沒有爲我工作。任何人都可以幫助以更快的速度移動紅色矩形。增加在畫布上圍繞圓移動recangle的速度

var canvas=document.getElementById("canvas"); 
 
     var ctx=canvas.getContext("2d"); 
 

 
     
 
     
 
     var cx=30; 
 
     var cy=30; 
 
     var rectWidth=10; 
 
     var rectHeight=2; 
 
     var rotation= 0; 
 
     requestAnimationFrame(animate); 
 
     function animate(){ 
 
     requestAnimationFrame(animate); 
 
     ctx.clearRect(0,0,canvas.width,canvas.height); 
 
     ctx.beginPath(); 
 
     ctx.arc(cx,cy,10,0,Math.PI*2); 
 
     ctx.closePath(); 
 
     ctx.fill(); 
 
     ctx.lineWidth = 5;  
 
     ctx.stroke(); 
 
     ctx.save(); 
 
     ctx.translate(cx,cy); 
 
     ctx.rotate(rotation); 
 
     ctx.strokeStyle= "red"; 
 
     ctx.strokeRect(-rectWidth/4+20,-rectHeight/2,rectWidth,rectHeight); 
 
     ctx.restore(); 
 

 
     rotation+=Math.PI/180; 
 
       
 
     }
<canvas id="canvas" width="60" height="60"></canvas>

+0

乘以也許因素旋轉? 'rotation + = Math.PI/180 * 10;' –

+0

Thanks Tahir Ahmed – pwalls

回答

0

在你animate功能,你必須被傳遞到rotate()方法的角度rotation

旋轉角度越多,獲得的速度越快。

下面是一個長方形以更高的速度移動您的片斷:(請注意,我已經改變了rotation值)

var canvas=document.getElementById("canvas"); 
 
var ctx=canvas.getContext("2d"); 
 
var cx=30; 
 
var cy=30; 
 
var rectWidth=10; 
 
var rectHeight=2; 
 
var rotation= 0; 
 
requestAnimationFrame(animate); 
 
function animate(){ 
 
    requestAnimationFrame(animate); 
 
    ctx.clearRect(0,0,canvas.width,canvas.height); 
 
    ctx.beginPath(); 
 
    ctx.arc(cx,cy,10,0,Math.PI*2); 
 
    ctx.closePath(); 
 
    ctx.fill(); 
 
    ctx.lineWidth = 5;  
 
    ctx.stroke(); 
 
    ctx.save(); 
 
    ctx.translate(cx,cy); 
 
    ctx.rotate(rotation); 
 
    ctx.strokeStyle= "red"; 
 
    ctx.strokeRect(-rectWidth/4+20,-rectHeight/2,rectWidth,rectHeight); 
 
    ctx.restore(); 
 
    rotation+=Math.PI/180 * 15;     
 
}
<canvas id="canvas" width="60" height="60"></canvas>