在 HTML5 Canvas 中旋转单个矩形

问题描述 投票:0回答:1

我有这个问题:我正在制作一个游戏,我需要在其他矩形之间旋转一个矩形(蓝色的)。

这是我的代码:

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")

//Making The Canvas Fullscreen :
canvas.width = innerWidth
canvas.height = innerHeight

//The rectangle I Need To Rotate :
c.fillStyle = "blue"
c.fillRect(0,0,canvas.width/3, canvas.height/3)

c.fillStyle = "red"
c.fillRect(canvas.width/3, canvas.height/3,canvas.width/3, canvas.height/3)
c.fillRect(canvas.width*2/3, canvas.height*2/3,canvas.width/3, canvas.height/3)

有解决办法吗???

javascript html canvas
1个回答
1
投票

当您只想将转换应用于一组有限的绘图操作时,通常会这样做:

  • ctx.save()
    保存初始状态
  • ctx.transform()
    .rotate
    .translate
    .skew
    .scale
    应用您所需的转换
  • 运行绘图命令
  • ctx.restore()
    恢复初始状态

因此,要将矩形围绕

(0, 0)
旋转 30 度,您可以这样做:

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")

canvas.width = innerWidth
canvas.height = innerHeight


ctx.save();
// 30 degree rotation around 0, 0
ctx.rotate(Math.PI / 6); 
ctx.fillStyle = "blue"
ctx.fillRect(0,0,canvas.width/3, canvas.height/3)
ctx.restore();

ctx.fillStyle = "red"
ctx.fillRect(canvas.width/3, canvas.height/3,canvas.width/3, canvas.height/3)
ctx.fillRect(canvas.width*2/3, canvas.height*2/3,canvas.width/3, canvas.height/3)
<canvas></canvas>

如果你想绕矩形中心旋转,你可以这样做:

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")

canvas.width = innerWidth
canvas.height = innerHeight


ctx.save();

const w = canvas.width / 3;
const h = canvas.height / 3;
ctx.translate(w / 2, h / 2);
ctx.rotate(Math.PI / 6);
ctx.fillStyle = "blue"
ctx.fillRect(-w / 2, -h / 2, w, h);
ctx.restore();

ctx.fillStyle = "red"
ctx.fillRect(canvas.width/3, canvas.height/3,canvas.width/3, canvas.height/3)
ctx.fillRect(canvas.width*2/3, canvas.height*2/3,canvas.width/3, canvas.height/3)
<canvas></canvas>

© www.soinside.com 2019 - 2024. All rights reserved.