引入下方的jquery.rotate.js文件,然後透過$("選擇器").rotate(角度);可以旋轉任意角度,
例如$("#rotate-image").rotate(45);把這句子放在$(document).ready(function(){ });中
就是將id為rotate-image的圖片旋轉45度。
不過,貌似在Chrome中總是不顯示。
唉,找了兩個小時,才發現Chrome太坑爹了,沒辦法取得圖片的長寬。
解決方法是,把$("#rotate-image").rotate(45);放在
$(window).load(function(){ });中,因為在Chrome中圖片在執行$(document ).ready(function(){ });中的語句時並沒有載入完圖片,坑爹啊。
另外可以更方便的透過呼叫$("選擇器").rotateRight()和$("選擇器").rotateLeft()來分別向右旋轉90度和向左旋轉90度。
jquery.rotate.js:
jQuery.fn.rotate = function(angle,whence) { var p = this.get(0); // we store the angle inside the image tag for persistence if (!whence) { p.angle = ((p.angle==undefined?0:p.angle) + angle) % 360; } else { p.angle = angle; } if (p.angle >= 0) { var rotation = Math.PI * p.angle / 180; } else { var rotation = Math.PI * (360+p.angle) / 180; } var costheta = Math.round(Math.cos(rotation) * 1000) / 1000; var sintheta = Math.round(Math.sin(rotation) * 1000) / 1000; //alert(costheta+","+sintheta); if (document.all && !window.opera) { var canvas = document.createElement('img'); canvas.src = p.src; canvas.height = p.height; canvas.width = p.width; canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')"; } else { var canvas = document.createElement('canvas'); if (!p.oImage) { canvas.oImage = new Image(); canvas.oImage.src = p.src; } else { canvas.oImage = p.oImage; } canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height); canvas.style.height = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width); var context = canvas.getContext('2d'); context.save(); if (rotation <= Math.PI/2) { context.translate(sintheta*canvas.oImage.height,0); } else if (rotation <= Math.PI) { context.translate(canvas.width,-costheta*canvas.oImage.height); } else if (rotation <= 1.5*Math.PI) { context.translate(-costheta*canvas.oImage.width,canvas.height); } else { context.translate(0,-sintheta*canvas.oImage.width); } context.rotate(rotation); context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height); context.restore(); } canvas.id = p.id; canvas.angle = p.angle; p.parentNode.replaceChild(canvas, p); } jQuery.fn.rotateRight = function(angle) { this.rotate(angle==undefined?90:angle); } jQuery.fn.rotateLeft = function(angle) { this.rotate(angle==undefined?-90:-angle); }
更多讓圖片旋轉任意角度及JQuery插件使用介紹相關文章請關注PHP中文網!