我有这个问题:我正在制作一个游戏,我需要在其他矩形之间旋转一个矩形(蓝色的)。
这是我的代码:
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)
有解决办法吗???
当您只想将转换应用于一组有限的绘图操作时,通常会这样做:
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>