Canvas How to - Rotate an image








Question

We would like to know how to rotate an image.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from   w  w w .java  2 s .c o m-->
    var ctx = canvas.getContext('2d'),
        img = document.createElement('img');
    img.onload = function() {
        canvas.height = img.height;
        canvas.width = img.width;
        // show original image to compare
        document.body.appendChild(img);
        // draw cropped image to canvas
        ctx.scale(-1,-1);
        ctx.drawImage(img, -img.width, -img.height);
        // to get the canvas to image:
        var dataUri = canvas.toDataURL();
    }
    img.src = 'http://www.java2s.com/style/download.png';
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: