rotate canvas using toDataURL

by Gustavo Carvalho

HTML

<div>
    <canvas id="one" width="100" height="200"></canvas>
</div>
<div>
    <button id="rotate">rotate canvas</button>
</div>

CSS

#one {
    border:1px solid red;
}

JavaScript

var canvas = document.getElementById("one");
    var context = canvas.getContext("2d");
    var cw = canvas.width;
    var ch = canvas.height;

    // Sample graphic
    context.beginPath();
    context.rect(10, 10, 20, 50);
    context.fillStyle = 'yellow';
    context.fill();
    context.lineWidth = 7;
    context.strokeStyle = 'black';
    context.stroke();

    // create button
    var button = document.getElementById("rotate");
    button.onclick = function () {
        // rotate the canvas 90 degrees each time the button is pressed
        rotate();
    }

    var myImageData, rotating = false;   

    var rotate = function () {
        if (!rotating) {
            rotating = true;
            myImageData = null;
            // store current data to an image
            myImageData = new Image();
            myImageData.src = canvas.toDataURL();

           myImageData.onload = function () {
                // reset the canvas with new dimensions
                canvas.width = ch;
                canvas.height = cw;
                cw = canvas.width;
                ch = canvas.height;

                context.save();
                // translate and rotate
                context.translate(cw, ch / cw);
                context.rotate(Math.PI / 2);
                // draw the previows image, now rotated
                context.drawImage(myImageData, 0, 0);               
                context.restore();
               
                rotating = false;
            }
        }
    }