web-utils-super
Version:
前端函数库
34 lines (32 loc) • 1.04 kB
JavaScript
/**
* @desc: 将图片资源转为base64
* @param {String} src 图片资源路径
* @param {String} type 图片类型,默认img 只支持 'img'|'jpeg'| 'webp'
* @param {Number} width 要生成的base64图片宽
* @param {Number} height 要生成的base64图片高
* @return {String}
*/
function imgToBase64(src, type = "png", width, height) {
return new Promise((resolve, reject) => {
let img = new Image();
img.src = src;
if (width) img.width = width;
if (height) img.height = height;
img.onload = () => {
try {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let dataURL = canvas.toDataURL(
type.indexOf("image") > -1 ? type : `image/${type}`
);
resolve(dataURL);
} catch (err) {
reject(err);
}
};
});
}
module.exports = imgToBase64;