1.先放上需要旋转的图片和旋转按钮
<img class="mb" id="img" style="width: 310px;" :src="imgPath">
<el-button size="mini" @click="rotate('img', 'right')" style="margin-bottom: 15px;">旋转</el-button>
注:@click="rotate('img', 'right')" 传需要旋转图片的id和需要旋转的方向; :src="imgPath" 绑定显示的图片
2.点击旋转按钮后执行的方法
rotate(pid, direction) {
//最小与最大旋转方向,图片旋转4次后回到原方向
var min_step = 0;
var max_step = 3;
var img = document.getElementById(pid);
if(img == null) return;
//img的高度和宽度不能在img元素隐藏后获取,否则会出错
let height = document.getElementById('image').height;
let width = document.getElementById('image').width;
console.log(height)
console.log(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');
console.log(step)
switch(step) {
case 0:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
break;
case 1:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height, width, height, );
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, 0, 0, -width, -height);
break;
case 3:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0, width, height);
break;
}
//将图片转为base64
var ss = canvas.toDataURL(0.92);
//将base64转为文件
this.dataURL = this.dataURLtoFile(ss);
},
3.将base64转为文件的方法:
dataURLtoFile(dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
console.log(mime)
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
},