In this tutorial you will know how to rotate images using JavaScript,First we add the image that we will rotate and the CANVAS tag, you can add this by the following markup:
Read The Full Tutorial.
In this tutorial you will know how to rotate images using JavaScript,First we add the image that we will rotate and the CANVAS tag, you can add this by the following markup:
<img src="/article-sources/images/plane-1.jpg" alt="" id="image" /> <canvas id="canvas"></canvas>
Now we will rotate the image using filters via DXImageTransform.Microsoft.BasicImage,This filter is easy to use but it is support only 4 angles
The code to rotate images for IE will look like this:
// Use DXImageTransform.Microsoft.BasicImage filter for MSIE >switch(degree){ case 0: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)'; break; case 90: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)'; break; case 180: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)'; break; case 270: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)'; break; }
And for browsers that support the CNAVAS tag, the code will look like this:
var cContext = canvas.getContext('2d');
var cw = img.width, ch = img.height, cx = 0, cy = 0; // Calculate new canvas size and x/y coorditates for image >switch(degree){ case 90: cw = img.height; ch = img.width; cy = img.height * (-1); break; case 180: cx = img.width * (-1); cy = img.height * (-1); break; case 270: cw = img.height; ch = img.width; cx = img.width * (-1); break; } // Rotate image canvas.setAttribute('width', cw); canvas.setAttribute('height', ch); cContext.rotate(degree * Math.PI / 180); cContext.drawImage(img, cx, cy);
We have to change the X/Y coordinates for drawImage function

|