我将在这里把工作中常用的工具方法整理出来
生成uuid
function getUuid(){
return `${Math.random().toString(32)}-${Date.now().toString(32)}`;
}
生成md5
import SparkMD5 from 'spark-md5';
function getMD5(file){
return new Promise(() => {
const fileReader = new FileReader();
// 读取文件
fileReader.readAsDataURL(file);
fileReader.onload = (e) => {
const contents = e.target.result;
const sparkMD5 = new SparkMD5();
sparkMD5.appendBinary(contents);
const MD5 = sparkMD5.end();
resolve(MD5);
}
fileReader.onerror = (e) => {
reject(e);
}
})
}
获取任意范围随机数
function random(min = 0,max = 1){
return Math.random() * (max - min) + min;
}
字符串转换
function stringToBlob(string){
const numberList = [];
for(let i = 0; i < string.length; i++){
numberList.push(string.charCodeAt(i));
}
const byteArr = new Uint8Array(numberList);
return new Blob([byteArr]);
}
十六进制颜色转换为rgb颜色
function hexToRGB(hex){
let alpha = false,
h = hex.slice(hex.startsWith("#") ? 1 : 0);
if(h.length === 3){
h = [...h].map(x => x + x).join('');
}else if(h.length === 8){
alpha = true;
}
h = parseInt(h,16);
return [
h >>> (alpha ? 24 : 16),
(h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8),
(h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 16 : 8),
]
}
rgb转换为十六进制颜色
function RGBTohex(rgb){
const RGBArr = rgb.split('b')[1].split('(')[1].split(')')[0].split(',');
let hex = '#'
RGBArr.forEach(item => {
if(+item > 16) hex += `0${(+item).toString(16)}`;
else hex += (+item).toString(16);
});
return hex;
}
解析富文本
function htmlDecode(input){
const ele = document.createElement('div');
ele.innerHTML = input;
return ele.childNodes.length === 0 ? '' : ele.childNodes[0].nodeValue;
}
图片转buffer
function dataURItoBlob(dataURI){
const byteString = atob(dataURI.split(',')[1]);
let mimeString = dataURI
.split(',')[0]
.split(':')[1]
.split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for(let i = 0; i < byteString.length; i++){
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab],{type:mimeString})
}