先上代码,直接可运行,不论是左旋转还是右旋转,顺序都不对。请问怎么解决这一问题?最后我需要返回base64位替换img里的值。
<div class="content">
<div class="box"><img src="图片地址" /><div class="rotate_img">旋转</div></div>
...有N个相同的DIV...
<div class="box"><img src="图片地址" /><div class="rotate_img">旋转</div></div>
</div>
// 点击rotate_img,即可旋转对应box中的图片
<!-- js 部分 -->
<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);
// var url = canvas.toDataURL();
// 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;
}
var url = canvas.toDataURL();
img.src = url;
}
</script>
先谢谢啦!~
我想告诉你 how and why,所以写了个原理向的小 demo,如果代码还是有疑惑,留言让我知道 (^ ^)
transform2d