2017-01-11 4 views
1

Я новичок в холсте, и я хочу изменить скорость движения красного прямоугольника вокруг круга, поскольку в настоящее время он движется медленно (60 кадров в секунду), а также я попытался 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>

+0

умножать вращение с коэффициентом возможно? 'rotation + = Math.PI/180 * 10;' –

+0

Спасибо Tahir Ahmed – pwalls

ответ

0

В вашей animate функции, у вас есть угол rotation который передается rotate() методы.

Больше угла поворота на, больше скорости вы получаете.

Ниже ваш фрагмент с прямоугольником движется с более высокой скоростью: (Обратите внимание, что я изменил значение 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>

Смежные вопросы