@mir_king/common
Version:
提供开发中常用的工具函数,提升开发效率的库
205 lines (202 loc) • 8.07 kB
JavaScript
import Vue from "vue";
const Prototype = Vue.prototype;
export const tools = {
// 路由返回
back(sum = -1) {
history.go(sum);
},
// 提示框
async confirm(title) {
try {
await Prototype.$confirm(title, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
});
return true;
} catch (err) {
return false;
}
},
// 请求host地址
host() {
return window.location?.origin || "";
},
// 将图片转换为Base64 url 图片链接 quality 压缩倍数 callback 回调
getImgToBase64(url, quality, callback) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image(); //通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,相比 createElement() 创建 <img> 省去了 append(),也就避免了文档冗余和污染
img.src = url;
img.setAttribute("crossOrigin", "Anonymous"); //url为外域时需要
//要先确保图片完整获取到,这是个异步事件
img.onload = function () {
canvas.height = img.height; //确保canvas的尺寸和图片一样
canvas.width = img.width;
ctx.drawImage(img, 0, 0); //将图片绘制到canvas中
let base64; // 图片长度
//压缩系数0-1之间
base64 = canvas.toDataURL("image/png", quality); //转换图片为dataURL,传第二个参数可压缩图片,前提是图片格式jpeg或者webp格式的
// console.log('压缩倍率', quality);
// 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定
// console.log('图片长度 大小', base64.length / 1024);
// while (base64.length / 1024 > 12) {
// quality -= 0.01;
// console.log('图片长度 大小', base64.length / 1024, quality);
// base64 = canvas.toDataURL('image/jpeg', quality);
// }
callback(base64); //调用回调函数
canvas = null;
};
},
//将base64转换为文件对象
dataURLtoFile(base64, filename) {
// 将base64按照 , 进行分割 将前缀 与后续内容分隔开
let data = base64.split(",");
// 利用正则表达式 从前缀中获取图片的类型信息(image/png、image/jpeg、image/webp等)
let type = data[0].match(/:(.*?);/)[1];
// 从图片的类型信息中 获取具体的文件格式后缀(png、jpeg、webp)
let suffix = type.split("/")[1];
// 使用atob()对base64数据进行解码 结果是一个文件数据流 以字符串的格式输出
const bstr = window.atob(data[1]);
// 获取解码结果字符串的长度
let n = bstr.length;
// 根据解码结果字符串的长度创建一个等长的整形数字数组
// 但在创建时 所有元素初始值都为 0
const u8arr = new Uint8Array(n);
// 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
while (n--) {
// charCodeAt():获取给定索引处字符对应的 UTF-16 代码单元
u8arr[n] = bstr.charCodeAt(n);
}
// 利用构造函数创建File文件对象
// new File(bits, name, options)
const file = new File([u8arr], `${filename}.${suffix}`, {
type: type,
});
// 将File文件对象返回给方法的调用者
return file;
// let arr = dataurl.split(",");
// let mime = arr[0].match(/:(.*?);/)[1];
// let bstr = atob(arr[1]);
// let n = bstr.length;
// let u8arr = new Uint8Array(n);
// while (n--) {
// u8arr[n] = bstr.charCodeAt(n);
// }
// //转换成file对象
// return new File([u8arr], filename, { type: mime });
//转换成成blob对象
//return new Blob([u8arr],{type:mime});
//将图片转换为base64,再将base64转换成file对象
// getImgToBase64("images/ruoshui.png", function (data) {
// let myFile = dataURLtoFile(data, "testimgtestimgtestimg");
// console.log(myFile);
// });
//压缩base64
// dealImage(base64, w, callback) {
// let newImage = new Image();
// let quality = 0.2; //压缩系数0-1之间
// newImage.src = base64;
// newImage.setAttribute('crossOrigin', 'Anonymous'); //url为外域时需要
// let imgWidth, imgHeight;
// newImage.onload = function () {
// imgWidth = 160;
// imgHeight = 90;
// let canvas = document.createElement('canvas');
// let ctx = canvas.getContext('2d');
// if (Math.max(imgWidth, imgHeight) > w) {
// if (imgWidth > imgHeight) {
// canvas.width = w;
// canvas.height = (w * imgHeight) / imgWidth;
// } else {
// canvas.height = w;
// canvas.width = (w * imgWidth) / imgHeight;
// }
// } else {
// canvas.width = imgWidth;
// canvas.height = imgHeight;
// quality = 0.6;
// }
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
// let base64 = canvas.toDataURL('image/jpeg', quality); //压缩语句
// // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定
// // while (base64.length / 1024 > 12) {
// // quality -= 0.01;
// // base64 = canvas.toDataURL('image/jpeg', quality);
// // }
// // 防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑
// // while (base64.length / 1024 < 50) {
// // quality += 0.001;
// // base64 = canvas.toDataURL("image/jpeg", quality);
// // }
// callback(base64); //必须通过回调函数返回,否则无法及时拿到该值,return拿不到
// // 调用方法
// // let base64 = res.data; //传入base64变量
// // console.log(base64.length, '11', base64); // 打印原长度
// // vm.dealImage(base64, 150, useImg);
// // function useImg(data) {
// // vm.formValidate.img = data;
// // console.log(vm.formValidate.img.length, '22', vm.formValidate.img); // 打印压缩长度
// // }
// };
// }
},
/**
* 函数防抖
* @param fn 事件触发的操作
* @param delay 间隔多少毫秒需要触发一次事件
*/
debounce(fn, delay) {
// 记录上一次的延时器
var timer = null;
var delay = delay || 200;
return function () {
var args = arguments;
var that = this;
// 清除上一次延时器
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(that, args);
}, delay);
};
},
/**
* 节流函数, 用于将多次执行变为每隔一段时间执行
*/
throttle2(fn, delay) {
let timer = null;
return function () {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, args);
clearTimeout(timer);
}, delay);
}
};
},
/**
* 深拷贝
* @param fn 事件触发的操作
* @param delay 间隔多少毫秒需要触发一次事件
*/
deepCopy(obj) {
let newobj = null; // 接受拷贝的新对象
if (typeof obj == "object" && typeof obj !== null) {
// 判断是否是引用类型
// newobj = obj instanceof Array ? [] : {}; // 判断是数组还是对象
if (obj !== null) {
newobj = obj instanceof Array ? [] : {}; // 判断是数组还是对象
}
for (var i in obj) {
newobj[i] = this.deepCopy(obj[i]); // 判断下一级是否还是引用类型
}
} else {
newobj = obj;
}
return newobj;
},
};