从十六进制中获取 r、g 和 b

Getting r, g and b from hex

我有一个十六进制颜色代码。 如何在 javascript 中从中获取 r、g 和 b 的值。 我尝试了很多,但 none 成功了,但我遇到了错误。 这是我试过的其中一个

function cutHex(h) {return (h[0]=="#") ? h.substring(1,7):h}
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}

报错

Uncaught TypeError: cutHex(...).substring is not a function

您的代码存在的一个问题是它只是天真地假设输入的格式有效。根据错误,您似乎根本没有向它传递字符串。例如,hexToR(123456) 会导致 cutHex 到 return number 123456,这确实没有 substring功能。

验证总是一个好主意。特别是对于用户输入,但对于程序员输入也是如此。

避免重复也是个好主意。你的代码看起来非常“复制粘贴”,因为你有三个不同的函数,它们都做同样的事情,只是输入的不同部分。

考虑到这两个因素,可以尝试以下方法:

/**
* Convert a hex string from #RRGGBB (or RRGGBB) to its component parts
* @param {string} hex #RRGGBB or RRGGBB
* @returns {[number,number,number]} RGB values in range 0-255
*/
function hexToRGB(hex) {
    if( typeof hex !== "string") throw new TypeError(`hexToRGB: string expected, got ${typeof hex}`);

    const match = hex.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
    if( !match) throw new Error(`hexToRGB: #RRGGBB expected, got ${hex}`);

    // now you have red, green, blue in match[1], match[2] and match[3] respectively
    // they're still in hex though, so...
    return match.slice(1).map(h=>parseInt(h,16));
}

此函数包含验证,如果您向此函数传递无效内容,将抛出有意义的错误,以帮助调试。另请注意记录此功能的 JSDoc,并允许您 IDE 在某些情况下自动检测潜在错误。