IE下及标准浏览器下的图片旋转(二)—— Canvas(2)
文章过长,一篇无法保存
IE下及标准浏览器下的图片旋转(二)—— Canvas(1)
同样,作为最后,我们使用使用jquery也为canvas写个旋转demo:
javascript:
$(function () {
var w = $("#pic").width();
var h = $("#pic").height();
var rot = 0;
function turn() {
if (!$("#cv").length)
$("#pic").after('<canvas id="cv"></canvas>')
var rotation = Math.PI * rot / 180;
if (rot == 90 || rot == 270) {
$("#cv").attr({"width": h, "height": w});
}
else {
$("#cv").attr({"width": w,"height": h});
}
$("#cv").css({
"position": "absolute",
"top": "50%",
"left": "50%",
"margin-top": function () {return -$(this).height()/2},
"margin-left": function () {return -$(this).width()/2}
});
var canvas = $("#cv")[0].getContext("2d");
var img = $("#pic")[0];
canvas.save();
switch (rot) {
case 0:
canvas.translate(0,0);
break;
case 90:
canvas.translate(h,0);
break;
case 180:
canvas.translate(w,h);
break;
case 270:
canvas.translate(0,w);
break;
}
canvas.rotate(rotation);
canvas.drawImage(img, 0, 0, w, h);
canvas.restore();
img.style.display = "none";
}
$("#turn_r").click(function() {
rot += 90;
turn();
if (rot == 270) {
rot = -90;
}
return false
});
$("#turn_l").click(function() {
rot -= 90;
if (rot == -90) {
rot = 270;
}
else if (rot == -180) {
rot = -rot;
}
turn();
return false
});
})
css:
#box {
width: 280px;
height: 200px;
position: relative;
text-align: center;
background: #f2f2f2;
}
#box a {
display: inline-block;
margin: 0 10px;
}
#box img {
position: absolute;
top: 50%;
left: 50%;
margin: -45px 0 0 -60px;
}
html:
<div id="box">
<a href="/" id="turn_l">左转</a>
<a href="/" id="turn_r">右转</a>
<img src="12.jpg" id="pic" alt="">
</div>
效果如图:
canvas标签只有现代浏览器支持,IE6-8并不支持,若想在IE6-8中使用,需要引入一个名为excanvas.js的文件。
excanvas主页:http://excanvas.sourceforge.net/
excanvas下载:http://code.google.com/p/explorercanvas/downloads/list
excanvas示例:http://developer.mozilla.org/en/docs/Canvas_tutorial
附:旋转角度,中心点,canvas宽高关系:
rotation = Math.PI * rot / 180;
c = Math.round(Math.cos(rotation) * 1000) / 1000;
s = Math.round(Math.sin(rotation) * 1000) / 1000;
canvas.height = Math.abs(c*h) + Math.abs(s*w);
canvas.width = Math.abs(c*w) + Math.abs(s*h);
if (rotation <= Math.PI/2) {
context.translate(s*h,0);
} else if (rotation <= Math.PI) {
context.translate(canvas.width,-c*h);
} else if (rotation <= 1.5*Math.PI) {
context.translate(-c*w,canvas.height);
} else {
context.translate(0,-s*w);
}
rotation弧度,rot角度,c,s系数
参考: