
最近突然想研究一下js旋轉(zhuǎn)圖片的功能。對於之前的實(shí)現(xiàn)方式,就不先說了?,F(xiàn)在HTML5很不錯,主要了解HTML5中的圖片旋轉(zhuǎn)吧。
實(shí)例示範(fàn):?
http://www.imqing.com/demo/rotateImg.html
原則:利用canvas物件來旋轉(zhuǎn)。
實(shí)作方式:先建立一個canvas元素,然後把img元素繪入canvas。但是,實(shí)際上,這是預(yù)設(shè)情況,就是圖片沒旋轉(zhuǎn)時。如果圖片要旋轉(zhuǎn)90度的話,就需要先把canvas畫布旋轉(zhuǎn)90度後再繪圖。
描述如下:?
內(nèi)部旋轉(zhuǎn)原理是這樣的,圖片的座標(biāo)是從左上角開始計算,向右為x正方向,向下為y正方向,在旋轉(zhuǎn)畫布canvas時,實(shí)際上是這個座標(biāo)在旋轉(zhuǎn),所以最後繪圖方式不一樣。
當(dāng)時我還用了picpick來測量旋轉(zhuǎn)一定角度後起點(diǎn)座標(biāo),才知道原來旋轉(zhuǎn)是這樣的。
程式碼:
<body>
<button onclick="rotateImg('testImg', 'left')">向左旋轉(zhuǎn)</button>
<button onclick="rotateImg('testImg', 'right')">向右旋轉(zhuǎn)</button><br/>
<img src="./test.jpg" id="testImg"/>
<script>
function rotateImg(pid, direction) {
//最小與最大旋轉(zhuǎn)方向,圖片旋轉(zhuǎn)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++;
//旋轉(zhuǎn)到原位置,即超過最大值
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);
}
//旋轉(zhuǎn)角度以弧度值為參數(shù)
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就不用解釋了吧,應(yīng)該。 rotate應(yīng)該也不用吧?關(guān)鍵是drawImage(img, x, y);
其中的x,y是指從哪一點(diǎn)開始畫,因為整個座標(biāo)系統(tǒng)旋轉(zhuǎn)了,所以,x,y不一樣,例如step=1
,圖片向右旋轉(zhuǎn)了90度,也就是座標(biāo)系旋轉(zhuǎn)了90度,那麼起始位置應(yīng)該是x = 0,?? y=? img.height
以上是如何利用HTML5 canvas旋轉(zhuǎn)圖片? (實(shí)例演示)的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!