具體函數的代碼就貼在下面了,三個參數
src:圖片鏈接,無論是url地址還是base64數據都可以
edg:旋轉角度,注意必須是90°的倍數,否則代碼報錯,非90°的旋轉的根據業務需要裁切裁切,用到的話小伙伴可以動動手修改一下函數
callback:因為img的load是個異步的,所以這才采取回調函數處理load成功的事件,回調的參數就是圖片旋轉后的base64的數據
function rotateBase64Img(src, edg, callback) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imgW;//圖片寬度
var imgH;//圖片高度
var size;//canvas初始大小
if (edg % 90 != 0) {
console.error("旋轉角度必須是90的倍數!");
throw '旋轉角度必須是90的倍數!';
}
(edg < 0) && (edg = (edg % 360) + 360)
const quadrant = (edg / 90) % 4; //旋轉象限
const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0}; //裁剪坐標
var image = new Image();
image.crossOrigin = "anonymous"
image.src = src;
image.onload = function () {
imgW = image.width;
imgH = image.height;
size = imgW > imgH ? imgW : imgH;
canvas.width = size * 2;
canvas.height = size * 2;
switch (quadrant) {
case 0:
cutCoor.sx = size;
cutCoor.sy = size;
cutCoor.ex = size + imgW;
cutCoor.ey = size + imgH;
break;
case 1:
cutCoor.sx = size - imgH;
cutCoor.sy = size;
cutCoor.ex = size;
cutCoor.ey = size + imgW;
break;
case 2:
cutCoor.sx = size - imgW;
cutCoor.sy = size - imgH;
cutCoor.ex = size;
cutCoor.ey = size;
break;
case 3:
cutCoor.sx = size;
cutCoor.sy = size - imgW;
cutCoor.ex = size + imgH;
cutCoor.ey = size + imgW;
break;
}
ctx.translate(size, size);
ctx.rotate(edg * Math.PI / 180);
ctx.drawImage(image, 0, 0);
var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
if (quadrant % 2 == 0) {
canvas.width = imgW;
canvas.height = imgH;
} else {
canvas.width = imgH;
canvas.height = imgW;
}
ctx.putImageData(imgData, 0, 0);
callback(canvas.toDataURL())
};
}
函數略大,不優雅,有什么不合理的地方歡迎小伙伴批評指正,共勵共勉。
