利用cavas压缩图片 // base 64 压缩处理图片大小getBase64(url, callback, outputFormat) { //通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,相比 createElement() 创建 省去了 append(
// base 64 压缩处理图片大小
getBase64(url, callback, outputFormat) {
//通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,相比 createElement() 创建 省去了 append(),也就避免了文档冗余和污染
let canvas = document.createElement('CANVAS');
let ctx = canvas.getContext('2d');
let imgs = new Image;
imgs.crossOrigin = 'Anonymous'; //移动端不支持,需要注掉
imgs.onload = function() {
let width = imgs.width;
let height = imgs.height;
// 按比例压缩0.8倍
let rate = (width < height ? width / height : height / width) / 0.63;
canvas.width = width * rate;
canvas.height = height * rate;
ctx.drawImage(imgs, 0, 0, width, height, 0, 0, width * rate, height * rate);
let dataURL = canvas.toDataURL(outputFormat || 'image/png', .8);
callback.call(this, dataURL);
canvas = null;
};
imgs.src = url;
},
