JS中RGB数值转换Hex

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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。