export function getRotateImg(url, deg = 0) {
return new Promise((resolve) => {
if (!deg || !(deg % 360)) {
resolve(url);
return;
}
const img = new Image();
img.src = url;
img.setAttribute("crossOrigin", "anonymous");
img.onload = function () {
const { width, height } = this;
const x = 0,
y = 0;
const canvas = document.createElement("canvas");
canvas.width = deg % 180 ? height : width;
canvas.height = deg % 180 ? width : height;
const ctx = canvas.getContext("2d");
ctx.save();
ctx.translate(x + canvas.width / 2, y + canvas.height / 2);
ctx.rotate(deg * (Math.PI / 180));
if (deg % 180) {
ctx.translate(-x - canvas.height / 2, -y - canvas.width / 2);
ctx.drawImage(img, x, y, canvas.height, canvas.width);
} else {
ctx.translate(-x - canvas.width / 2, -y - canvas.height / 2);
ctx.drawImage(img, x, y, canvas.width, canvas.height);
}
ctx.restore();
const src = canvas.toDataURL("image/png");
resolve(src);
};
});
}
前端图片旋转90/180/270/360度,并生成新的图片url
于 2023-03-29 17:29:00 首次发布