先说一下为什么要旋转的目的:因为在画布上签名,在不同的设备上我需要不同方向的签名图片,电脑是横屏,手机就是竖屏,所以需要把手机的签名旋转270°,因此写了这个方法。
关于画布旋转的重点就是获取到你的画布元素在 onload 函数里面调用图片旋转的方法
里面的methods.imageRotate就是旋转方法,只是基于vue3写的所以有methods
$("#file").attr("src", canvas.value.toDataURL("image/png"));
const fileImg = document.getElementById("file")
fileImg.onload = function () {
const imgValue = methods.imageRotate(fileImg, 270)
// console.log("imgValue", imgValue)
}
图片旋转的封装方法
//图片旋转
imageRotate(img, rotate) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
switch (rotate) {
case 90: // 旋转90°
canvas.width = img.height;
canvas.height = img.width;
ctx.rotate((90 * Math.PI) / 180);
ctx.drawImage(img, 0, -img.height, img.width, img.height);
break;
case 180: // 旋转180°
canvas.width = img.width;
canvas.height = img.height;
ctx.rotate((180 * Math.PI) / 180);
ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
break;
case 270: // 旋转270°
canvas.width = img.height;
canvas.height = img.width;
ctx.rotate((-90 * Math.PI) / 180);
ctx.drawImage(img, -img.width, 0, img.width, img.height);
break;
default:
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
break;
}
return canvas.toDataURL("image/png");
},
注:改方法并不会改变画布上的内容,是新建了一个变量来存储。
* 千万记住要在onload调用