Rotate square on its axis in HTML5 Canvas?

auroranil picture auroranil · Jan 20, 2012 · Viewed 10.6k times · Source

I want to create a function that rotates a square on its axis.

var halfWidth = canvas.width/2;
var halfHeight = canvas.height/2;

var x = halfWidth-10;
var y = halfHeight-10;
var w = 20;
var h = 20;
var deg = 45;

rotate(x, y, w, h, deg);

ctx.fillRect(x, y, w, h);

The function:

function rotate(x, y, w, h, deg) {
    // ctx.translate() and ctx.rotate()
    // goes here.
}

How to do this?

Answer

auroranil picture auroranil · Jan 21, 2012

Thanks dr.dredel for the link.

var cx = canvas.width/2;
var cy = canvas.height/2;

var x = -10;
var y = -10;
var w = 20;
var h = 20;
var deg = 45;

ctx.save();

ctx.translate(cx, cy);
ctx.rotate(deg * Math.PI/180);

ctx.fillRect(x, y, w, h);

ctx.restore();

Explanation:

  • ctx.save() saves the current state of the coordinate system.

  • ctx.translate(cx, cy) changes the origin to the center of canvas

  • ctx.rotate(deg * Math.PI/180) rotates the square to 45 degrees (Note that the parameter is in radians, not degrees)

  • ctx.fillRect( x, y, w, h ) draws the square

  • ctx.restore() restores the last state of the coordinate system.

JS Fiddle link.

Another JS Fiddle link, with a HTML5 slider.