I have this problem: I am making a game and I need to rotate a single rectangle (the blue one) between other rectangles.
Here is my code:
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)
Any Solve ???
When you want to apply a transformation to only a limited set of drawing operations, you usually do:
ctx.save()
to save the initial statectx.transform()
, .rotate
, .translate
, .skew
or .scale
to apply your desired transformationctx.restore()
to restore the initial stateSo, to rotate your rectangle 30 degrees around (0, 0)
, you would do:
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>
If you want to rotate around the rectangle's center, you could do:
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>