Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html rotate entire canvas by 90 degrees

I have an image drawn to an html cavas. I would like to be able to rotate the image by 90 degrees but I can't seem to find an example on how to rotate the entire canvas image, only an object on the canvas.

Does anyone have example code to rotate an entire canvas by 90 degrees?

I accepted an anwser below but wanted to provide additional example code : http://jsfiddle.net/VTyNF/1/

<canvas id="myCanvas" width="578" height="200"></canvas>

<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  context.translate(canvas.width/2,canvas.height/2) 
  context.rotate(90 * (Math.PI / 180));   
  context.beginPath();
  context.rect(188 - canvas.width/2, 50 - canvas.height/2, 200, 100);
  context.fillStyle = 'yellow';
  context.fill();
  context.lineWidth = 7;
  context.strokeStyle = 'black';
  context.stroke();
</script>
like image 522
Kyle Avatar asked Aug 08 '13 04:08

Kyle


2 Answers

You would have to apply this rotation before you draw your canvas. You can't rotate anything that is already drawn.

So:

To rotate a canvas, the content.rotate() expects a value in radians. So first, lets make it simple by converting degrees to radians using:

function getRadianAngle(degreeValue) {
    return degreeValue * Math.PI / 180;
} 

You may want to translate the canvas first before rotating so that it's origin is set correctly.

context.translate(context.width/2,context.height/2);

Once we know what value we want, we simply rotate the canvas before we draw anything!

Please note, in your example, the rectangle you have drawn, is also being offset in the first two parameters of context.rect(X,Y,W,H)`.

I find it's easier to set widths as variables, then do simple math to re position the box automatically, notice now it sits perfectly in the center, and rotates nicely!

DEMO: http://jsfiddle.net/shannonhochkins/VTyNF/6/

like image 180
Shannon Hochkins Avatar answered Nov 14 '22 22:11

Shannon Hochkins


Say your canvas element has id "foo". In JavaScript you could do something like this:

var canvas = document.getElementById('foo'),
    context = canvas.getContext('2d');

// Rotates the canvas 90 degrees
context.rotate(90 * (Math.PI / 180));
like image 35
federico-t Avatar answered Nov 14 '22 22:11

federico-t