2015年10月19日
(转)原生JavaScript+Jquery控制图片旋转自定义角度
摘要: 对于用管了CS3的矩阵变化,突然有一天项目要求兼容IE9回过头发现,IE9以至于IE9-以下都不兼容,于是就收集了一些文章,一起学习一下
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);
}
一小段代码封装了一个rotate()函数,在$(“选择器名称”).rotate(跟上你想要旋转的角度);
注意这里有几个小问题不支持 :
1.在封装前一定要引用Jquery,否者不好意思不生效,
2. 一定要放在$(document).ready(function(){ });中 ,不然在Chrome中不显示( 没法获取图片的长宽 )
3. 这个效果只能执行一次,你会想问什么只能一次?这不是坑爹么!!
当你想进行第二次执行时候你发现他竟然变成了” 画布 “,成了画布就没法搞了
4.IE6-8不支持
谢谢