其他分享
首页 > 其他分享> > color:rgb/rgba 16进制互转

color:rgb/rgba 16进制互转

作者:互联网

// rgb/rgba 转 16进制
const hexify = (color) => { let values = color .replace(/rgba?\(/, '') .replace(/\)/, '') .replace(/[\s+]/g, '') .split(','); let a = parseFloat(values[3] || 1), r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255), g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255), b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255); return "#" + ("0" + r.toString(16)).slice(-2) + ("0" + g.toString(16)).slice(-2) + ("0" + b.toString(16)).slice(-2); }
// 16进制转rgba
const colorRgb = (colorHex, opacityVal = 1) => {
    // 16进制颜色值的正则
    let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
    // 把颜色值变成小写
    let color = colorHex.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 "rgba(" + colorChange.join(",") + ',' + opacityVal + ")"
    } else {
        return color;
    }
}

 

标签:slice,16,color,let,rgba,互转,values
来源: https://www.cnblogs.com/guiyh/p/16387805.html