class Colorutil {
//RGBtoHex方法将r,g,b数值转换为#hex形式
static RGBtoHex(r, g, b) {
let hex = r << 16 | g << 8 | b;
return "#" + hex.toString(16);
}
//HextoRGB将#hex转换为rgb(r,g,b)格式
static HextoRGB(hexStr) {
let hex = 0;
if (hexStr.charAt(0) == "#") {
if(hexStr.length == 4){
//检测诸如#FFF简写格式
hexStr = "#" + hexStr.charAt(1).repeat(2) +
hexStr.charAt(2).repeat(2) +
hexStr.charAt(3).repeat(2);
}
hex = parseInt(hexStr.slice(1), 16);
}
let r = hex >> 16 & 0xFF;
let g = hex >> 8 & 0xFF;
let b = hex & 0xFF;
let rgb = `rgb(${r},${g},${b})`;
return rgb;
}
}
//@example
let hex = Colorutil.RGBtoHex(255, 0, 0);
let rgb = Colorutil.HextoRGB("#FF0000");
console.log(hex); //#ffff00
console.log(rgb); //rgb(255,0,0)
网友评论