rgb,hex 相互转换 JS(JavaScript)

rgb,hex 色彩相互转换

/**
     * 转化为RGB 为 HEX
     * @param {string} data 如:rgb(0,0,0)
     */
function colorHex(data) {
    // RGB颜色值的正则 
    let reg = /^(rgb|RGB)/;
    let color = data;
    if (reg.test(color)) {
        let strHex = "#";
        // 把RGB的3个数值变成数组 
        let colorArr = color.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
        // 转成16进制 
        for (let i = 0; i < colorArr.length; i++) {
            let hex = Number(colorArr[i]).toString(16);
            if (hex.length == "1") { hex = "0" + hex; }
            strHex += hex;
        }
        return strHex;
    }
    else { return color.toString(); }
}

/**
 * 转化为HEX 为RGB
 * @param {string} data 如:#ffffff、#fff
 */
function colorRgb(data) {
    // 16进制颜色值的正则 
    let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 把颜色值变成小写 
    let color = data.toLowerCase();
    if (reg.test(color)) {
        // 如果只有三位的值,需变成六位,如:#fff => #ffffff 
        if (color.length === 4) {
            let colorNew = "#";
            for (let i = 1; i < 4; i += 1) {
                colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
            }
            color = colorNew;
        }
        // 处理六位的颜色值,转为RGB 
        let colorChange = [];
        for (let i = 1; i < 7; i += 2) {
            colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
        }
        return "RGB(" + colorChange.join(",") + ")";
    } else { return color; }
}

你可能感兴趣的:(rgb,hex 相互转换 JS(JavaScript))