簡體   English   中英

提高在畫布中圍繞圓圈移動的速度

[英]Increase speed of moving recangle around circle in canvas

我是畫布的新手,我想改變圍繞圓圈移動紅色矩形的速度,因為它正在緩慢移動(60fps)並且我也嘗試了setTimeout但是對我來說沒有用。 任何人都可以幫助以更快的速度移動紅色矩形。

  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> 

在您的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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM