善用 IIFE 以封装 BOM 对象提供的方法
浏览器为我们提供了许多有用的方法,为了使用这些方法,开发者通常需要创建对应的对象,往往使得业务代码显得冗长,缺乏经验的开发者对所建对象的处理方式也显得不够“优雅”。
如果对 IIFE 返回的函数可以保存其既有作用域链这一特性善加利用,就可以将这些对象的创建过程“隐藏”起来,使得业务代码更加清晰简洁。
1. 文件转 Base64
/**
* @method blob2Base64 - 将 blob 文件转为 Base64 URL
* @returns {Promise}
* */
const blob2Base64 = (() => {
const fileReader = new FileReader();
let resolver = null, errHandler = null;
fileReader.onload = () => resolver(fileReader.result);
fileReader.onerror = err => errHandler(err);
return file => {
fileReader.readAsDataURL(file);
return new Promise((resolve, reject) => {
resolver = resolve;
errHandler = reject;
})
}
})();
const readFileFromInput = async event => {
const { target: { files: [file] }} = event;
const base64 = await blob2Base64(file);
console.log('read data as base64:', base64);
}
document.querySelector('input[type="file"]').addEventListener('change', readFileFromInput);
2. 从URL加载图片
/**
* @const loadImageFromURL - 从 URL 加载图片
* */
const loadImageFromURL = (() => {
const image = new Image();
image.setAttribute('crossOrigin', 'Anonymous');
let resolver = null, errHandler = null;
image.onload = () => {
resolver(image);
};
image.onerror = err => {
errHandler(err);
};
return URL => {
return new Promise((resolve, reject) => {
resolver = resolve;
errHandler = reject;
image.src = URL;
});
}
})();
3. 获取图片BitMap数据
/**
* @method imageFileToImageData - 读取图片文件的为位图数据
* @param {File} blob - 需要转换的文件对象
* @return {Promise}
*/const imageFileToImageData = (() => {
const canvas = document.createElement('canvas');
canvas.setAttribute('crossOrigin', 'Anonymous');
const context = canvas.getContext('2d');
return async blob => {
const image = await loadImageFromURL(await blob2Base64(blob));
const { width, height } = image;
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
context.drawImage(image, 0, 0, width, height);
return context.getImageData(0, 0, width, height);
};
})();
4. 文件下载
/**
* 传入 URL 下载文件
* */
const downLoadPicByURL = (() => {
const anchor = document.createElement('a');
return (URL, filename = 'download') => {
anchor.setAttribute('href', URL);
anchor.setAttribute('download', filename);
anchor.click();
}
})();
评论