javaxp微博中的图片旋转我就是参看下面的代码做的:
说明:图片的旋转都是通过操作画布(canvas),但是IE和其他浏览器不一样的地方在于IE通过filter操作,其他浏览器直接改变其属性值就可以了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>JavaScript Demos - Rotate Image using Canvas</title> <script type="text/javascript" src="jquery-1.8.2.min.js"></script> <script type="text/javascript"> var img = null, canvas = null; $(document).ready(function(){ // Initialize image and canvas img = document.getElementById('image'); canvas = document.getElementById('canvas'); if(!canvas || !canvas.getContext){ canvas.parentNode.removeChild(canvas); } else { img.style.position = 'absolute'; img.style.visibility = 'hidden'; } rotateImage(0); // Handle clicks for control links $('#resetImage').click(function(){ rotateImage(0); }); $('#rotate90').click(function(){ rotateImage(90); }); $('#rotate180').click(function(){ rotateImage(180); }); $('#rotate270').click(function(){ rotateImage(270); }); }); function rotateImage(degree) { if(document.getElementById('canvas')){ 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); } else { // 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; } } } </script> <style type="text/css"> </style> </head> <body> <div id="page"> <h1>How to Rotate Images using JavaScript</h1> <div> <img src="1.jpg" alt="" id="image" /> <canvas id="canvas"></canvas> </div> <p> <strong>Rotate Image: </strong> <a href="javascript:;" id="resetImage">Reset Image</a> <a href="javascript:;" id="rotate90">90°</a> <a href="javascript:;" id="rotate180">180°</a> <a href="javascript:;" id="rotate270">270°</a> </p> </body> </html>