Rotate image keeping canvas = image size

by Gregor Z.

HTML

<div id="cont">
    <canvas id="canvas"></canvas>
</div>
<button id="left" disabled>CCW</button>
<button id="right" disabled>CW</button>

CSS

#cont {
    width:250px;
    height:250px;
}
#canvas {
    border:1px solid #c00;
}

JavaScript

/// load an image
var img = new Image,
    canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    
    /// store angles (0, 90, 180, 270) in an array
    angles = [0 * Math.PI, 0.5 * Math.PI, Math.PI, 1.5 * Math.PI],
    index = 0;

img.onload = start;
img.src = 'http://i.imgur.com/sAyE5ZE.png';

function start() {

    /// set size and draw image
    renderImage();
    
    /// set up buttons
    left.disabled = false;
    right.disabled = false;

    left.onclick = rotateCCW;
    right.onclick = rotateCW;
}

function rotateCCW() {
    index--;      /// decrement index of array
    if (index < 0) index = angles.length -1;
    renderImage();
}
function rotateCW() {
    index++;     /// increment index of array
    if (index >= angles.length) index = 0;
    renderImage();
}

function renderImage() {

    /// use index to set canvas size
    switch(index) {
        case 0:
        case 2:
            /// for 0 and 180 degrees size = image
            canvas.width = img.width;
            canvas.height = img.height;
            break;
        case 1:
        case 3:
            /// for 90 and 270 canvas width = img height etc.
            canvas.width = img.height;
            canvas.height = img.width;
            break;
    }

    /// get stored angle and center of canvas    
    var angle = angles[index],
        cw = canvas.width * 0.5,
        ch = canvas.height * 0.5;
    
    /// rotate context
    ctx.translate(cw, ch);
    ctx.rotate(angle);
    ctx.translate(-img.width * 0.5, -img.height * 0.5);
    
    /// draw image and reset transform
    ctx.drawImage(img, 0, 0);
    ctx.setTransform(1, 0, 0, 1, 0, 0);
}