在Javascript中将rgb字符串转换为十六进制

Nei*_*eil 19 javascript rgb hex

我正在使用TweenMax JS库和ColorPropsPlugin,它将补间以多种格式指定的颜色值,我遇到的问题是结果总是以字符串的形式:

"rgb(255,255,255)"
Run Code Online (Sandbox Code Playgroud)

如何将其转换为十六进制数字,如:

0xffffff
Run Code Online (Sandbox Code Playgroud)

Nip*_*pey 31

我首先会删除CSS部分:

var a = "rgb(255,255,255)".split("(")[1].split(")")[0];
Run Code Online (Sandbox Code Playgroud)

然后将其拆分为单独的数字:

a = a.split(",");
Run Code Online (Sandbox Code Playgroud)

将单个数字转换为十六进制

var b = a.map(function(x){             //For each array element
    x = parseInt(x).toString(16);      //Convert to a base16 string
    return (x.length==1) ? "0"+x : x;  //Add zero if we get only one character
})
Run Code Online (Sandbox Code Playgroud)

并将它粘合在一起:

b = "0x"+b.join("");
Run Code Online (Sandbox Code Playgroud)


Tim*_*own 7

以下内容改编Colour自我编写和使用的类,但由于它处理百分比和负数,因此可能对您的需求有些过分.

演示:http://jsfiddle.net/5ryxx/1/

码:

function componentFromStr(numStr, percent) {
    var num = Math.max(0, parseInt(numStr, 10));
    return percent ?
        Math.floor(255 * Math.min(100, num) / 100) : Math.min(255, num);
}

function rgbToHex(rgb) {
    var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;
    var result, r, g, b, hex = "";
    if ( (result = rgbRegex.exec(rgb)) ) {
        r = componentFromStr(result[1], result[2]);
        g = componentFromStr(result[3], result[4]);
        b = componentFromStr(result[5], result[6]);

        hex = "0x" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }
    return hex;
}
Run Code Online (Sandbox Code Playgroud)


bob*_*obo 6

这就是我做的.

String.prototype.toRGB = function() {

  var rgb = this.split( ',' ) ;
  this.r=parseInt( rgb[0].substring(4) ) ; // skip rgb(
  this.g=parseInt( rgb[1] ) ; // this is just g
  this.b=parseInt( rgb[2] ) ; // parseInt scraps trailing )

}
Run Code Online (Sandbox Code Playgroud)

运行后'rgb(125,181,215)'.toRGB(),您将获得.r,.g.b返回在同一字符串对象中定义的属性(具有正确的整数值).

要获取十六进制值,只需使用 yourNumber.toString(16);


Sla*_*lai 5

rgb2Hex = s => s.match(/[0-9]+/g).reduce((a, b) => a+(b|256).toString(16).slice(1), '0x')

console.log(rgb2Hex('rgb(10, 11, 12)'), rgb2Hex('rgb(255, 256, 257)'))
Run Code Online (Sandbox Code Playgroud)


不建议用于不可靠的用户输入,但字符串也可以作为函数进行计算:

rgb = (r, g, b) => '0x' + (1<<24|r<<16|g<<8|b).toString(16).slice(1)

console.log(eval('rgb(10, 11, 12)'), eval('rgb(255)'))
Run Code Online (Sandbox Code Playgroud)