码迷,mamicode.com
首页 > Web开发 > 详细

rotate.js实现图片旋转 (chrome,IE,firefox都可以实现)

时间:2015-09-01 13:50:13      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

找了好多资料,要么是IE可以用,但是谷歌不行,,还有就是两个都可以用的,图片大小显示不全。终于找到一个好一点的js,先贴一下代码。

1.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);
}

 2.页面中的实现  

<div id="buttons">
<a href="javascript:void(0);" id="btn_right" onclick="flip()">旋转</a>
</div>
<div id="img_area" style="width:370px;height:210px;" >
<img src="./images/1.png" alt="旋转图片" id="image" style="width:370px;height:210px;"/>
</div>
<script src=‘./lx/jquery.js‘></script>

<script src=‘./lx/rotate.js‘></script>

3.实现JS(后面更改的宽度是为了固定图片大小的)

function flip(){
  $("#image").rotate(180);
  $("#image").width(‘370px‘);
  $("#image").height(‘220px‘);
}

rotate.js实现图片旋转 (chrome,IE,firefox都可以实现)

标签:

原文地址:http://www.cnblogs.com/zlx7/p/4775342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!