올바른 트랙에있는 것 같습니다.
- 저장 (rectX, rectY)
- 회전
- fillRect 할 번역 (-rectWidth/2, -rectHeight/2, rectWidth는 rectHeight가) //이/중앙 회전
승 RECT을 그립니다
-
- 여러 직사각형
복원
,363,210
이 같은 일부 사각형 객체를 정의하는 경우 : 당신이하는 구형의 각도를 증가 그래서 만약 초당 60 프레임에 대한
requestAnimationFrame(animate);
function animate(time){
// call for another loop in the animation
requestAnimationFrame(animate);
// clear canvas and redraw all rects
ctx.clearRect(0,0,cw,ch);
for(var i=0;i<rects.length;i++){
// draw this rect at its specified angle
var rect=rects[i];
ctx.save();
ctx.translate(rect.x+rect.w/2,rect.y+rect.h/2);
ctx.rotate(rect.angle);
ctx.fillStyle=rect.color;
ctx.fillRect(-rect.w/2,-rect.h/2,rect.w,rect.h);
ctx.restore();
// increase this rect's angle for next time
rect.angle+=(Math.PI*2)/60;
}
}
requestAnimationFrame
루프에서 :
는
var rects=[];
rects.push({x:50,y:50,w:50,h:35,color:'green',angle:0});
rects.push({x:150,y:120,w:30,h:20,color:'blue',angle:0});
그럼 당신은이 같은 애니메이션 프레임에 넣어 수 있습니다 (Math.PI * 2)/60에 의해 각 루프에서 매초마다 약 1 회전을 회전시킵니다.
예 코드와 데모 :
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var rects=[];
rects.push({x:50,y:50,w:50,h:35,color:'green',angle:0});
rects.push({x:150,y:120,w:30,h:20,color:'blue',angle:0});
requestAnimationFrame(animate);
function animate(time){
// call for another loop in the animation
requestAnimationFrame(animate);
// clear canvas and redraw all rects
ctx.clearRect(0,0,cw,ch);
for(var i=0;i<rects.length;i++){
// draw this rect at its specified angle
var rect=rects[i];
ctx.save();
ctx.translate(rect.x+rect.w/2,rect.y+rect.h/2);
ctx.rotate(rect.angle);
ctx.fillStyle=rect.color;
ctx.fillRect(-rect.w/2,-rect.h/2,rect.w,rect.h);
// orientation symbol
ctx.fillStyle='red';
ctx.fillRect(-rect.w/2,-rect.h/2,5,5)
ctx.restore();
// increase this rect's angle for next time
rect.angle+=(Math.PI*2)/60;
}
}
function drawRect(rect){
ctx.save();
ctx.translate(rect.x+rect.w/2,rect.y+rect.h/2);
ctx.rotate(rect.angle);
ctx.fillStyle=rect.color;
ctx.fillRect(-rect.w/2,-rect.h/2,rect.w,rect.h);
ctx.restore();
rect.angle+=deltaAngle;
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>