随机生成16进制颜色值和RGB颜色值及其相互转换

前言

随机生成十六进制颜色值和RGB颜色值以及两者之间的转换方法。

十六进制(HEX)颜色值的随机生成

1
2
3
4
5
6
7
8
function randomHex(){
var arrHex=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],
strHex="#";
for(var i=0;i < 6; i++){
strHex+=arrHex[Math.round(Math.random()*15)];
}
return strHex;
}

十进制(RGB)颜色值随机生成

1
2
3
4
5
6
function randomRgb() {
var r = Math.round(Math.random() * 255),
g = Math.round(Math.random() * 255),
b = Math.round(Math.random() * 255)
return "rgb("+r+","+g+","+b+")";
}

HEX颜色值转RGB颜色值

1
2
3
4
5
6
function hexToRgb(value) {
var r = parseInt(value.slice(1,3),16),
g = parseInt(value.slice(3,5),16),
b = parseInt(value.slice(5,7),16);
return "rgb("+r+","+g+","+b+")";
}

RGB颜色值转HEX颜色值

1
2
3
4
5
6
7
8
function rgbToHex(value) {
var rbgArr = value.slice(4,-1).split(","),
r = parseInt(rbgArr[0]).toString(16),
g = parseInt(rbgArr[1]).toString(16),
b = parseInt(rbgArr[2]).toString(16);
console.log(rbgArr)
return "#"+r+g+b;
}