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?
Thanks dr.dredel for the link.
Explanation:
ctx.save()saves the current state of the coordinate system.ctx.translate(cx, cy)changes the origin to the center of canvasctx.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 squarectx.restore()restores the last state of the coordinate system.JS Fiddle link.
Another JS Fiddle link, with a HTML5 slider.