Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rotate a Canvas containing an Image by 90, 180, 270 Degrees?

I have an HTML5 canvas which contains an image. Now I want to rotate this canvas by x degrees.

What I did was:

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

var rotateCanvas = function(canvas, image, degrees) {
  var context = canvas.getContext('2d');
  context.rotate(getRadianAngle(degrees));
  context.drawImage(image, 0, 0);
  return canvas;            
}

var image = new Image();
image.onload = function() {
   var canvas = document.createElement("canvas");
   var context = canvas.getContext('2d');
   var cw = canvas.width = image.width;
   var ch = canvas.height = image.height;
   context.drawImage(image, 0, 0, image.width, image.height);

   rotateCanvas(canvas, image, 180);
}
image.src = // some image url;

This code does not work correctly.

How can I define a rotate function to rotate a canvas?

Edit: I do not want to use css because I need the canvas for further processing.

like image 625
confile Avatar asked Sep 14 '25 10:09

confile


1 Answers

Rotating the canvas can be done with CSS, but that might mess up your page design if the canvas is rectangular rather than square.

It's probably better to rotate your image on the canvas.

  • Clear the existing canvas.
  • Translate to the rotation point--x=image.x+image.width/2,y=image.y+image.height/2.
  • Rotate.
  • drawImage(image,-image.width/2,-image.height/2

Example code and a Demo: http://jsfiddle.net/m1erickson/8uRaL/

BTW, the radians for your desired angles are:

  • 0 degrees == 0 radians
  • 90 degrees == Math.PI/2 radians
  • 180 degrees == Math.PI radians
  • 270 degrees == Math.PI*3/2 radians

Example code:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

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

    var radians=0;

    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/cat.png";
    function start(){
        animate();
    }


    function animate(){
        requestAnimationFrame(animate);
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.save();
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(radians);
        ctx.drawImage(img,-img.width/2,-img.height/2);
        ctx.restore();
        radians+=Math.PI/180;
    }


}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
like image 173
markE Avatar answered Sep 16 '25 23:09

markE