Canvas Transformations 2

by Francisco Maria Calisto

HTML

<canvas id="canvas" width="300" height="300"></canvas>

CSS

canvas {
    border: 1px red solid;
}

JavaScript

var ctx = document.getElementById('canvas').getContext('2d');
for (var x = 0.5; x < 300; x += 10) {ctx.moveTo(x, 0);ctx.lineTo(x, 300);}for (var y = 0.5; y < 300; y += 10) {ctx.moveTo(0, y);ctx.lineTo(300, y);}ctx.strokeStyle = "#ddd";ctx.stroke(); // Grid

var ctx = document.getElementById('canvas').getContext('2d');

// left rectangles, rotate from canvas origin
ctx.save();
// blue rect
ctx.fillStyle = "#0095DD";
ctx.fillRect(30,30, 100, 100); 
ctx.rotate((Math.PI/180)*25);
// grey rect
ctx.fillStyle = "#4D4E53";
ctx.fillRect(30,30, 100, 100);
ctx.restore();

// right rectangles, rotate from rectangle center
// draw blue rect
ctx.fillStyle = "#0095DD";
ctx.fillRect(150, 30, 100, 100);  

ctx.translate(200, 80); // translate to rectangle center 
// x = x + 0.5 * width
// y = y + 0.5 * height
ctx.rotate((Math.PI/180)*25); // rotate
ctx.translate(-200, -80); // translate back

// draw grey rect
ctx.fillStyle = "#4D4E53";
ctx.fillRect(150, 30, 100, 100);