图片旋转并保存图片
let degree = this.rotate;
if (degree === 0) {
this.$message({ message: ‘图片未旋转’, offset: 100 });
return;
}
const img = new Image();
// 获取图片src
img.src = this.currentBigPhoto.img;
// 获取图片的宽高
const imgInfo = this.$refs['detail'].getBoundingClientRect();
if (!imgInfo) {
return;
}
const imgWidth = imgInfo.width;
const imgHeight = imgInfo.height;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 获取要旋转的角度
// 旋转360度 0度
if (degree === 0) {
canvas.width = imgWidth;
canvas.height = imgHeight;
// ctx.rotate((0 * Math.PI) / 180);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
} else if (degree === 90) {
// 旋转90度
canvas.height = imgHeight;
canvas.width = imgWidth;
ctx.rotate((90 * Math.PI) / 180);
ctx.drawImage(img, 0, -imgWidth, imgHeight, imgWidth);
} else if (degree === 180) {
// 旋转180
canvas.width = imgWidth;
canvas.height = imgHeight;
ctx.rotate((180 * Math.PI) / 180);
ctx.drawImage(img, -imgWidth, -imgHeight, imgWidth, imgHeight);
} else if (degree === 270) {
// 旋转270
canvas.width = imgWidth;
canvas.height = imgHeight;
ctx.rotate((270 * Math.PI) / 180);
ctx.drawImage(img, -imgHeight, 0, imgHeight, imgWidth);
}
// 生成图片的url
const newImg = canvas.toDataURL();
// this.a = newImg;
// 重置页面图片的旋转度数
this.rotate = 0;
// 新图替换当前图片
this.currentBigPhoto.img = newImg;
// 替换存储中的图片
this.replaceImg(this.currentBigPhoto.id);