颜色
随机色,编码类型转换,参考网上文章,没有照搬别人的,自己进行总结
十六进制 => RGB
// 颜色:十六进制转RPG function colorHexToRgb(color, isObj) { if (!color) return ''; const r = parseInt(color.slice(1, 3), 16); const g = parseInt(color.slice(3, 5), 16); const b = parseInt(color.slice(5, 7), 16); const a = 1; if (isObj) return { r, g, b, a }; return `rgba( ${r}, ${g}, ${b}, ${a} )`; } const a = colorHexToRgb('#F0F8FF') const b = colorHexToRgb('#F0F8FF', true) console.log(a, b);
RGB => 十六进制
function colorRgbToHex(rgba) { const value = rgba.match(/([\d|\.]+)/g) const obj = { r: Number(value[0]), g: Number(value[1]), b: Number(value[2]), } return '#' + ((1 << 24) + (obj.r << 16) + (obj.g << 8) + obj.b).toString(16).slice(1); } console.log(colorRgbToHex('rgba( 174, 0, 22, 0.6 )')); console.log(colorRgbToHex('rgb( 174, 0, 22 )')); console.log(colorRgbToHex('rgba( 174, 0, 22, 1 )'));
随机色rgba
// 随机颜色rgba;alpha: 透明度 function randomColorRgba(alpha = 1) { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); return `rgba( ${r}, ${g}, ${b}, ${alpha} )`; }
随机色十六进制
// 随机颜色十六进制 function randomColorHex() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); let color = r.toString(16) + g.toString(16) + b.toString(16) if (color.length <= 5) color = '0' + color return '#' + color; }
通过正则把rgba的值都提取出来
// 获取rgba值 function getRgbaValue(rgba) { // 通过正则把rgba的值都提取出来 const value = rgba.match(/([\d|\.]+)/g) return { r: Number(value[0]), g: Number(value[1]), b: Number(value[2]), a: Number(value[3]) || 1, } } console.log(getRgbaValue('rgba( 174, 0, 22, 0.6 )'));