rotate canvas using toDataURL
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 myImage, rotating = false;
var rotate = function () {
if (!rotating) {
rotating = true;
// store current data to an image
myImage = new Image();
myImage.src = canvas.toDataURL();
console.log(canvas.toDataURL())
myImage.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(myImage, 0, 0);
context.restore();
// clear the temporary image
myImage = null;
rotating = false;
}
}
}