Canvas How to - Click to rotate image








Question

We would like to know how to click to rotate image.

Answer


<!DOCTYPE html>
<html>
<body>
  <canvas id="canvas"></canvas>
<script type='text/javascript'>//<![CDATA[ 
var can = document.getElementById('canvas');
        var ctx = can.getContext('2d');
        var img = new Image();
        img.onload = function(){<!--from  w  w w. ja v a 2s  .c  om-->
            can.width = img.width;
            can.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);
        }
        img.src = 'http://www.java2s.com/style/download.png';
        can.onclick = function() {
            ctx.translate(img.width-1, img.height-1);
            ctx.rotate(Math.PI);
            ctx.drawImage(img, 0, 0, img.width, img.height);
        };
        document.write(can.toDataURL());
//]]>  
</script>
</body>
</html>

The code above is rendered as follows: