十六(16)进制与rgb颜色转换
# 十六进制转换为RGB
# 方法一
Hex(十六进制)、Dec(十进制)、Octal(八进制)、Bin(二进制)
const 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 (
'rgb' +
(alpha ? 'a' : '') +
'(' +
(h >>> (alpha ? 24 : 16)) +
', ' +
((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +
', ' +
((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
(alpha ? `, ${h & 0x000000ff}` : '') +
')'
);
};
console.log(hexToRGB('#27ae60'));//rgba(39, 174, 96)
console.log(hexToRGB('27ae60'));//rgb(39, 174, 96)
console.log(hexToRGB('#7b2243'));//rgb(123, 34, 67)
console.log(hexToRGB('#fff')); //rgb(255, 255, 255)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 方法二
Hex(十六进制)、Dec(十进制)、Octal(八进制)、Bin(二进制)
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
// 在这里输入十六进制颜色----'#ffffff' 可通过游览器 console 查看 rgb
console.log( hexToRgb( '#ffffff' ) ); //return { r : 255, g : 255, b : 255 }
console.log( hexToRgb( '#eeeeee' ) ); //return { r : 238, g : 238, b : 238 }
console.log( hexToRgb( '#00a7ff' ) ); //return { r : 0, g : 167, b : 255 }
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 方法三
function getRgbVal(str){
let arr = []
let rex = /^#[A-Za-z0-9]{6}$/
if(!rex.test(str)){
alert('请输入正确的颜色编码')
return
}
str = str.replace(/\#/,'')
for(let i=0; i < str.length; i=i+2){
console.log(str.substr(i, 2),'2222')
arr.push(Number('0x' + str.substr(i, 2)))
}
console.log('输出的RGB值为:' + arr.join(','))
}
getRgbVal('#FFB6C1')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# RGB转换为十六进制
const RGBToHex = (r, g, b) => {
return "#" + ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
}
console.log(RGBToHex(39, 174, 96)); // #27ae60
console.log(RGBToHex(123,34,67));//#7b2243
console.log(RGBToHex(255, 255, 255));//#ffffff
1
2
3
4
5
6
2
3
4
5
6
# 随机生成随机十六进制颜色
function generateRandomHexColor() {
let colorGenerated = "#" + (Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6);
if (colorGenerated !== "#0000ff" && colorGenerated !== "#ff0000") {
return colorGenerated;
}
colorGenerated = "#" + (Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6);
}
console.log(generateRandomHexColor())
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13