canvas导出旋转图片

327 阅读1分钟

;

const Reg = /^(?:data:image\/){1}(?:\w)+?(?:;base64,){1}.+$/

/* export default */ function rotate(f, d = 0) {

// 1.在模块开发中可以把export default打开使用

// 2.旋转图片是一个异步函数,通过.then获取旋转后的图片信息

// 3.旋转函数接受两个参数

// 4.第一个参数:图片文件,支持文件格式或者base64

// 5.第二个参数是需要旋转的角度,需要输入数字

d = parseInt(d % 360);

const Cas = document.createElement('canvas');

Cas.style.display = 'none';

const Ctx = Cas.getContext('2d');

const Img = document.createElement('img');

Img.style.display = 'none';

const FR = new FileReader();

return new Promise((resolve, reject) => {

let type = 'image/png';

let pristine = '';

try {

function ImgLoad() {

Img.removeEventListener('load', ImgLoad);

const w = Img.width;

const h = Img.height;

const sinW = Math.round(Math.abs(Math.sin(Math.PI * d / 180).toFixed(5)) * w);

const sinH = Math.round(Math.abs(Math.sin(Math.PI * d / 180).toFixed(5)) * h);

const cosW = Math.round(Math.abs(Math.cos(Math.PI * d / 180).toFixed(5)) * w);

const cosH = Math.round(Math.abs(Math.cos(Math.PI * d / 180).toFixed(5)) * h);

const width = cosW + sinH;

const height = sinW + cosH;

let x = 0;

let y = 0;

if ((0 < d && d < 90) || (d <= -270 && -360 <= d)) {

x = sinH;

y = 0;

} else if ((90 <= d && d < 180) || (d <= -180 && -270 < d)) {

x = sinH + cosW;

y = cosH;

} else if ((180 <= d && d < 270) || (d <= -90 && -180 < d)) {

x = cosW;

y = sinW + cosH;

} else if ((270 <= d && d <= 360) || (d < 0 && -90 < d)) {

x = 0;

y = sinW;

}

let base64 = pristine;

if (d != 0) {

Cas.width = width;

Cas.height = height;

Ctx.translate(x, y);

Ctx.rotate(Math.PI * d / 180);

Ctx.drawImage(Img, 0, 0);

base64 = Cas.toDataURL(type);

}

resolve({

worked: {

width,

height,

base64,

},

pristine: {

width: w,

height: h,

base64: pristine,

},

})

}

Img.addEventListener('load', ImgLoad);

if (Reg.test(f)) {

Img.src = f;

pristine = f;

type = f.split(';')[0].split(':')[1];

} else {

function FRload() {

FR.removeEventListener('load', FRload);

pristine = FR.result;

Img.src = pristine;

type = f.type;

}

FR.addEventListener('load', FRload);

FR.readAsDataURL(f);

}

} catch (error) {

reject(error);

}

})

}