Canvas How to - Rotate Image on Canvas








Question

We would like to know how to rotate Image on Canvas.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<style type='text/css'>
canvas {<!--from   w ww . ja  v a  2s .c  o  m-->
  border: 1px solid red;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var angleInDegrees=0;
    var image=document.createElement("img");
    image.onload=function(){
        ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
    }
    image.src="http://www.java2s.com/style/download.png";
    $("#clockwise").click(function(){ 
        angleInDegrees+=90;
        drawRotated(angleInDegrees);
    });
    $("#counterclockwise").click(function(){ 
        angleInDegrees-=90;
        drawRotated(angleInDegrees);
    });
    function drawRotated(degrees){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.save();
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(degrees*Math.PI/180);
        ctx.drawImage(image,-image.width/2,-image.width/2);
        ctx.restore();
    }
});
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=300></canvas>
  <br>
  <button id="clockwise">Rotate right</button>
  <button id="counterclockwise">Rotate left</button>
</body>
</html>

The code above is rendered as follows: