HTML5 Canvas Image Rotation


As I have done some research on HTML5 canvas with image rotation.
Found that  we can rotate the canvas to left, right and mirror the image in just few lines of code.

<!DOCTYPE HTML>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rotate Canvas</title>
<script type="text/javascript">
function rotate(p_deg)
{

switch(p_deg) {
   default :
   case 0 :
canvas.setAttribute('width', image.width);
canvas.setAttribute('height', image.height);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, 0, 0);
break;
   case 90 :
canvas.setAttribute('width', image.height);
canvas.setAttribute('height', image.width);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, 0, -image.height);
break;
   case 180 :
canvas.setAttribute('width', image.width);
canvas.setAttribute('height', image.height);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, -image.width, -image.height);
break;
   case 270 :
   case -90 :
canvas.setAttribute('width', image.height);
canvas.setAttribute('height', image.width);
canvasContext.rotate(p_deg * Math.PI / 180);
canvasContext.drawImage(image, -image.width, 0);
break;
};
}
</script>
</head>
<body>
<p>
rotate:
    <input type="button" value="0°"  onclick="rotate(0);" />
    <input type="button" value="90°"  onclick="rotate(90);" />
    <input type="button" value="180°"  onclick="rotate(180);" />
    <input type="button" value="-90°"  onclick="rotate(-90);" />
</p>
<canvas id="canvas">Your Browser doesn't support canvas</canvas>
<p> Orginal Image</p>
<img id="image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnFAUav2b7rd51Qpdjl8i1ChXPV1lfLbVigmP8rZ-6QsxkjwR6MWQzRWlg6Mn371nRYC2e2KFtFJSuh_k_ZK8IB-ceSbFFNxg9gFaTnVb68Cj-ga2eK9LYNvT2T_MFN-MNwJv-51q3GG0/s320/Karva+Chauth.jpg" alt="" />
<script type="text/javascript">
var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(image, 10, 10);
</script>
</body>
</html>


All the best guys........

Post a Comment

Analytics