js 十六进制颜色转 rgb 颜色


比如:1、#04c304转rgb(0,0,0)。2、0x04c304转rgb(0,0,0)

convertHexToRgb(hexColor) {
    if (hexColor.indexOf('#') != -1) {
        // 移除可能存在的 "#" 符号
        hexColor = hexColor.replace(/^#/, '');
        // 将十六进制值转换为十进制值
        const red = parseInt(hexColor.substr(0, 2), 16);
        const green = parseInt(hexColor.substr(2, 2), 16);
        const blue = parseInt(hexColor.substr(4, 2), 16);
        // 返回 RGB 格式的字符串
        return `rgb(${red}, ${green}, ${blue})`;
    } else {
        // 移除可能存在的 "0x" 前缀
        hexColor = hexColor.replace(/^0x/, '');
        // 将十六进制值转换为十进制值
        const red = parseInt(hexColor.substr(0, 2), 16);
        const green = parseInt(hexColor.substr(2, 2), 16);
        const blue = parseInt(hexColor.substr(4, 2), 16);
        // 返回 RGB 格式的字符串
        return `rgb(${red}, ${green}, ${blue})`;
    }
}

276

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创

转载:转载请注明原文链接 - js 十六进制颜色转 rgb 颜色

评论
孙瑞杰生日