JavaScript 如何将十六进制转换为RGBA值

JavaScript 如何将十六进制转换为RGBA值

给定一个颜色的十六进制代码,任务是将Hex值转换为RGBA值。以下是利用JavaScript讨论的一些常用技术。

方法1

  • 首先通过正则表达式检查传递的Hex值是否有效。
  • 然后使用 .slice()方法 获取“#”后的Hex值内容,并使用 .split()方法 将Hex值的每个字符存储在数组中。
  • 如果数组的长度为3(例如#fff,#aaa),则将其存储为相应的值(即#ffffff,#aaaaaa),使长度变为6。
  • 根据规则将代码转换为十六进制,例如前两个字符属于红色值,中间两个字符属于绿色值,依此类推。

示例: 以下示例使用上述方法。

const hexValue = '#fbafff';

function convertHexToRgbA(hexVal) {
    let ret;

    // If the hex value is valid.
    if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hexVal)) {

        // Getting the content after '#',
        // eg. 'ffffff' in case of '#ffffff'
        ret = hexVal.slice(1);

        // Splitting each character
        ret = ret.split('');

        // Checking if the length is 3
        // then make that 6
        if (ret.length == 3) {
            let ar = [];
            ar.push(ret[0]);
            ar.push(ret[0]);
            ar.push(ret[1]);
            ar.push(ret[1]);
            ar.push(ret[2]);
            ar.push(ret[2]);
            ret = ar;
        }

        // Starts with '0x'(in hexadecimal)
        ret = '0x' + ret.join('');

        // Converting the first 2 characters
        // from hexadecimal to r value
        let r = (ret >> 16) & 255;

        // Converting the second 2 characters
        // to hexadecimal to g value
        let g = (ret >> 8) & 255;

        // Converting the last 2 characters
        // to hexadecimal to b value
        let b = ret & 255;

        // Appending all of them to make
        // the RGBA value
        return 'rgba(' + [r, g, b].join(',') + ',1)';
    }
}

function myFunc() {
    console.log("The RGBA value of '"
        + hexValue + "' is '" +
        convertHexToRgbA(hexValue) + "'");
}

myFunc();

输出

The RGBA value of '#fbafff' is 'rgba(251,175,255,1)'

方法2

  • 使用 .slice()方法 获取前2个字符并将其转换为十六进制。
  • 对于其余的代码,重复步骤1。
  • 将它们拼接在一起并返回最终值。

示例: 此示例使用上述方法。

const hexValue = '#fbafff';

function convertHexToRgbA(hex, a) {

    // Convert the first 2 characters to hexadecimal
    let r = parseInt(hex.substring(1, 3), 16),

        // Convert the middle 2 characters to hexadecimal
        g = parseInt(hex.substring(3, 5), 16),

        // Convert the last 2 characters to hexadecimal
        b = parseInt(hex.substring(5, 7), 16);

    // Append them all
    return "rgba(" + r + ", " + g + ", "
        + b + ", " + a + ")";
}

function myFunc() {
    console.log("The RGBA value of '"
        + hexValue + "' is '" +
        convertHexToRgbA(hexValue, 1) + "'");
}

myFunc();

输出

The RGBA value of '#fbafff' is 'rgba(251, 175, 255, 1)'

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程