前端常用的工具方法,转blob、颜色互转等

我将在这里把工作中常用的工具方法整理出来

生成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})
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值