如何在画布中同时旋转两个矩形

How to rotate 2 rectangles in a canvas at the same time?

本文关键字:两个 旋转 布中同      更新时间:2023-09-26

我知道我可以使用"translate-rate-translate-back-fillrect"过程来旋转一个矩形。

但是,如果我想同时旋转它们,并有一个时间间隔()使它们每秒自动旋转,该怎么办?

每次尝试绘制时,我都试图保存和恢复,但都没有成功。

你似乎走在了正确的轨道上

  • 保存
  • 平移(rectX,rectY)
  • 旋转
  • fillRect(-rerectWidth/2,-rerectHeight/2,rectWidth,rectHeight)//绘制带有中心旋转的矩形
  • 恢复

对于多个矩形

如果你像这样定义一些矩形对象:

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);
        ctx.restore();
        // increase this rect's angle for next time
        rect.angle+=(Math.PI*2)/60;
    }
}

requestAnimationFrame循环速度约为60fps,因此如果将每个循环中矩形的角度增加(Math.PI*2)/60,则将使矩形每秒旋转一整圈。

示例代码和演示:

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>