
最近突然想研究一下js旋轉圖片的功能。對于之前的實現方式,就不先說了。現在HTML5很不錯,主要了解一下HTML5中的圖片旋轉吧。
原理:利用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






