rotateImg () {
if (this.curImageUrl) {
this.rotateNum++;
let degree = 0;
let rotateInput = this.rotateNum * 90;
degree += parseInt(rotateInput);
degree %= 360;
let img = new Image();
img.setAttribute("crossOrigin",'Anonymous');
img.src = this.curImageUrl;
img.onload = () => {
let $w = img.width, $h = img.height, $c = document.getElementById("uploadImageCanvas");
let ctx = $c.getContext("2d");
if (degree === 90) {
$c.width = $h;
$c.height = $w;
ctx.clearRect(0, 0, $h, $w);
ctx.rotate(degree / 180 * Math.PI);
ctx.translate(0, -$h);
ctx.drawImage(img, 0, 0);
} else if (degree === 270) {
$c.width = $h;
$c.height = $w;
ctx.clearRect(0, 0, $h, $w);
ctx.rotate(degree / 180 * Math.PI);
ctx.translate(-$w, 0);
ctx.drawImage(img, 0, 0);
} else {
$c.width = $w;
$c.height = $h;
ctx.clearRect(0, 0, $w, $h);
ctx.translate($w / 2, $h / 2);
ctx.rotate(degree / 180 * Math.PI);
ctx.translate(-$w / 2, -$h / 2);
ctx.drawImage(img, $w / 2 - $w / 2, $h / 2 - $h / 2);
}
$c.toBlob((blob) => {
let fd = new FormData();
let fileBlob = new File([blob], new Date().getTime() + '.png')
fd.append("file", fileBlob);
handUpload(fd).then(res => {
console.log(res)
})
});
}
} else {
this.rotateNum = 0;
}
}
实例是,操作canvas上图片旋转的。