Search code examples
javascripthtmlcanvas

Rotating A Single Rectangle in HTML5 Canvas


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 ???


Solution

  • When you want to apply a transformation to only a limited set of drawing operations, you usually do:

    • ctx.save() to save the initial state
    • ctx.transform(), .rotate, .translate, .skew or .scale to apply your desired transformation
    • run the drawing commands
    • ctx.restore() to restore the initial state

    So, 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>