美文网首页
JS中RGB数值转换Hex

JS中RGB数值转换Hex

作者: 浅笑19 | 来源:发表于2020-06-11 09:41 被阅读0次
    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)
    

    相关文章

      网友评论

          本文标题:JS中RGB数值转换Hex

          本文链接:https://www.haomeiwen.com/subject/gxvvtktx.html