Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate the existing content of HTML5 canvas?

Is there a way to rotate the existing content of HTML5 canvas by Javascript? I know it's possible to rotate an image that will be drawn on to canvas, but I want to rotate the content that has been drawn on to canvas, for example, a 200x200 corner of a 400x400 canvas, or any specific region of an existing canvas.

Same question to scale the existing canvas content...

I know getImageData/putImageData provide a potential to transform the pixel array, but it's just too slow and inefficient.

like image 767
Tony T Avatar asked Dec 15 '11 09:12

Tony T


1 Answers

It's pretty easy to do with a temp canvas.

Live Demo

Live Demo Animated (just for the heck of it)

The above example draws 2 boxes, then rotates and scales from 0,0 to 200,200

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

canvas.width = canvas.height = 400;

// fill the canvas black, and draw 2 boxes
ctx.fillStyle = "#000";
ctx.fillRect(0,0,400,400);
ctx.fillStyle = "rgb(255,0,0)";

ctx.fillRect(10,10,190,190);
ctx.fillStyle = "rgb(255,255,0)";
ctx.fillRect(250,250,90,90);

// Create a temp canvas to store our data (because we need to clear the other box after rotation.
var tempCanvas = document.createElement("canvas"),
    tempCtx = tempCanvas.getContext("2d");

tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
// put our data onto the temp canvas
tempCtx.drawImage(canvas,0,0,canvas.width,canvas.height);

// Append for debugging purposes, just to show what the canvas did look like before the transforms.
document.body.appendChild(tempCanvas);

// Now clear the portion to rotate.
ctx.fillStyle = "#000";
ctx.fillRect(0,0,200,200);
ctx.save();
// Translate (190/2 is half of the box we drew)
ctx.translate(190/2, 0);
// Scale
ctx.scale(0.5,0.5);  
// Rotate it
ctx.rotate(45*Math.PI/180);
// Finally draw the image data from the temp canvas.
ctx.drawImage(tempCanvas,0,0,200,200,10,10,190,190);
ctx.restore();
like image 181
Loktar Avatar answered Sep 28 '22 07:09

Loktar