您的位置:首页 > Web前端 > HTML5

利用HTML5 canvas旋转图片

2012-09-18 22:04 405 查看
最近突然想研究一下js旋转图片的功能。对于之前的实现方式,就不先说了。现在HTML5很不错,主要了解一下HTML5中的图片旋转吧。

实例演示:

http://www.imqing.com/demo/rotateImg.html

原理:利用canvas对象来旋转。

实现方式:首先创建一个canvas元素,然后把img元素绘入canvas。但是,实际上,这是默认情况,就是图片没旋转时。如果图片要旋转90度的话,就需要先把canvas画布旋转90度后再绘图。

描述如下: (内部旋转原理是这样的,图片的坐标是从左上角开始计算,向右为x正方向,向下为y正方向,在旋转画布canvas时,实际上是这个坐标在旋转,所以最后绘图方式不一样。当时我还用了picpick来测量旋转一定角度后起点坐标,才知道原来旋转是这样的,嘿嘿。)

代码:

<body>
<button onclick="rotateImg('testImg', 'left')">向左旋转</button>
<button onclick="rotateImg('testImg', 'right')">向右旋转</button><br/>
<img src="./test.jpg" id="testImg"/>
<script>
function rotateImg(pid, direction) {
//最小与最大旋转方向,图片旋转4次后回到原方向
var min_step = 0;
var max_step = 3;
var img = document.getElementById(pid);
if (img == null)return;
//img的高度和宽度不能在img元素隐藏后获取,否则会出错
var height = img.height;
var width = img.width;
var step = img.getAttribute('step');
if (step == null) {
step = min_step;
}
if (direction == 'right') {
step++;
//旋转到原位置,即超过最大值
step > max_step && (step = min_step);
} else {
step--;
step < min_step && (step = max_step);
}
img.setAttribute('step', step);
var canvas = document.getElementById('pic_' + pid);
if (canvas == null) {
img.style.display = 'none';
canvas = document.createElement('canvas');
canvas.setAttribute('id', 'pic_' + pid);
img.parentNode.appendChild(canvas);
}
//旋转角度以弧度值为参数
var degree = step * 90 * Math.PI / 180;
var ctx = canvas.getContext('2d');
switch (step) {
case 0:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
break;
case 1:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height);
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height);
break;
case 3:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0);
break;
}
}
</script>
</body>

解释: canvas.width与height就不用解释了吧,应该。rotate应该也不用吧?关键是

drawImage(img, x, y);


其中的x,y是指从哪一点开始画,因为整个坐标系统旋转了,所以,x,y不一样,比如step=1,图片向右旋转了90度,即坐标系旋转了90度,那么起始位置应该是

x = 0,   y=  img.height


其它类似可得。是不是觉得很简单呢?

请看http://www.imqing.com/blog/wp/2012/09/html5-canvas-rotate-image/
本文出自 “Qing's web” 博客,请务必保留此出处http://qings.blog.51cto.com/4857138/997998
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: