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

实例演示:

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

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

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

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

代码:

<body><buttononclick="rotateImg('testImg','left')">向左旋转</button><buttononclick="rotateImg('testImg','right')">向右旋转</button><br/><imgsrc="./test.jpg"id="testImg"/><script>functionrotateImg(pid,direction){//最小与最大旋转方向,图片旋转4次后回到原方向varmin_step=0;varmax_step=3;varimg=document.getElementById(pid);if(img==null)return;//img的高度和宽度不能在img元素隐藏后获取,否则会出错varheight=img.height;varwidth=img.width;varstep=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);varcanvas=document.getElementById('pic_'+pid);if(canvas==null){img.style.display='none';canvas=document.createElement('canvas');canvas.setAttribute('id','pic_'+pid);img.parentNode.appendChild(canvas);}//旋转角度以弧度值为参数vardegree=step*90*Math.PI/180;varctx=canvas.getContext('2d');switch(step){case0:canvas.width=width;canvas.height=height;ctx.drawImage(img,0,0);break;case1:canvas.width=height;canvas.height=width;ctx.rotate(degree);ctx.drawImage(img,0,-height);break;case2:canvas.width=width;canvas.height=height;ctx.rotate(degree);ctx.drawImage(img,-width,-height);break;case3: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

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