从 Javascript 中的 rgb 字符串获取颜色分量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10970958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a color component from an rgb string in Javascript?
提问by Ryan Peschel
I'm using Javascript and Canvas to make a painting app and was using strings in this format to designate chosen colors:
我正在使用 Javascript 和 Canvas 制作一个绘画应用程序,并使用这种格式的字符串来指定所选颜色:
"rgb(255,0,0)"
"rgb(255,0,0)"
Because the canvas context fillStyle property takes in strings of that format.
因为画布上下文 fillStyle 属性接受该格式的字符串。
However, I now need to obtain individual components from this string and was wondering if there was a way to do it without messy string manipulation. Possibly some built in way to convert that string to a sort of color object and then access its r, g, and b components?
但是,我现在需要从这个字符串中获取单个组件,并且想知道是否有一种方法可以在不进行混乱的字符串操作的情况下做到这一点。可能有一些内置的方法可以将该字符串转换为一种颜色对象,然后访问它的 r、g 和 b 组件?
Thanks.
谢谢。
回答by Jared Farrish
NOTE- We're all on board with the regex ate my brains and kicked my dogattitude, but the regex version just seems the better method. My opinion. Check it out.
注意- 我们都同意正则表达式吃了我的大脑并踢了我的狗的态度,但正则表达式版本似乎是更好的方法。我的看法。一探究竟。
Non-regex method:
非正则表达式方法:
var rgb = 'rgb(200, 12, 53)';
rgb = rgb.substring(4, rgb.length-1)
.replace(/ /g, '')
.split(',');
console.log(rgb);
http://jsfiddle.net/userdude/Fg9Ba/
http://jsfiddle.net/userdude/Fg9Ba/
Outputs:
输出:
["200", "12", "53"]
Or... A really simple regex:
或者...一个非常简单的正则表达式:
EDIT: Ooops, had an i
in the regex for some reason.
编辑:哎呀,i
由于某种原因在正则表达式中有一个。
var rgb = 'rgb(200, 12, 53)';
rgb = rgb.replace(/[^\d,]/g, '').split(',');
console.log(rgb);
回答by Ryan Peschel
much simpler way ..
更简单的方法..
var rgb = 'rgb(200, 12, 53)'.match(/\d+/g);
console.log(rgb);
and here comes the output as
输出如下
["200", "12", "53"]
" simple is always beautiful! " :)
“简单总是美丽的!”:)
回答by B T
How about using a color library like the xolor library:
xolor("rgb(200,100,40)").r // returns the red part
回答by Brian Peacock
My version takes a HEX
, RGB
or RGBa
string as an argument, uses no regEx, and returns an object with red, green, and blue (and alpha for RGBa
) number-values.
我的版本需要HEX
,RGB
或RGBa
字符串作为参数,不使用正则表达式,并用红,绿,蓝(与阿尔法返回一个对象RGBa
)数量的值。
var RGBvalues = (function() {
var _hex2dec = function(v) {
return parseInt(v, 16)
};
var _splitHEX = function(hex) {
var c;
if (hex.length === 4) {
c = (hex.replace('#','')).split('');
return {
r: _hex2dec((c[0] + c[0])),
g: _hex2dec((c[1] + c[1])),
b: _hex2dec((c[2] + c[2]))
};
} else {
return {
r: _hex2dec(hex.slice(1,3)),
g: _hex2dec(hex.slice(3,5)),
b: _hex2dec(hex.slice(5))
};
}
};
var _splitRGB = function(rgb) {
var c = (rgb.slice(rgb.indexOf('(')+1, rgb.indexOf(')'))).split(',');
var flag = false, obj;
c = c.map(function(n,i) {
return (i !== 3) ? parseInt(n, 10) : flag = true, parseFloat(n);
});
obj = {
r: c[0],
g: c[1],
b: c[2]
};
if (flag) obj.a = c[3];
return obj;
};
var color = function(col) {
var slc = col.slice(0,1);
if (slc === '#') {
return _splitHEX(col);
} else if (slc.toLowerCase() === 'r') {
return _splitRGB(col);
} else {
console.log('!Ooops! RGBvalues.color('+col+') : HEX, RGB, or RGBa strings only');
}
};
return {
color: color
};
}());
console.debug(RGBvalues.color('rgb(52, 86, 120)'));
//-> { r: 52, g: 86, b: 120 }
console.debug(RGBvalues.color('#345678'));
//-> { r: 52, g: 86, b: 120 }
console.debug(RGBvalues.color('rgba(52, 86, 120, 0.67)'));
//-> { r: 52, g: 86, b: 120, a: 0.67 }
console.debug(RGBvalues.color('#357'));
//-> { r: 51, g: 85, b: 119 }
Might be useful to someone. :)
可能对某人有用。:)
回答by kennebec
Even if you are sure the colors will be in rgb format, and not rgbA, hex, color name, or hsl, you can still have 'rgb(25%,55%,100%)'.
即使您确定颜色将采用 rgb 格式,而不是 rgbA、十六进制、颜色名称或 hsl,您仍然可以使用 'rgb(25%,55%,100%)'。
function Rgb(rgb){
if(!(this instanceof Rgb)) return new Rgb(rgb);
var c= rgb.match(/\d+(\.\d+)?%?/g);
if(c){
c= c.map(function(itm){
if(itm.indexOf('%')!= -1) itm= parseFloat(itm)*2.55;
return parseInt(itm);
});
}
this.r= c[0];
this.g= c[1];
this.b= c[2];
}
var c= Rgb('rgb(10%,25%,55%)'); alert([c.r, c.g, c.b])
var c= Rgb('rgb(10%,25%,55%)'); 警报([cr,cg,cb])
note- If you are using canvas, you have map.
注意 - 如果您使用的是画布,则您有地图。
otherwise-
除此以外-
Array.prototype.map=Array.prototype.map || function(fun, scope){
var T= this, L= T.length, A= Array(L), i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in T){
A[i]= fun.call(scope, T[i], i, T);
}
++i;
}
return A;
}
}
回答by Julien Le Coupanec
For people using a color picker, this library also allows to convert colors in many formats: https://tovic.github.io/color-picker/
对于使用颜色选择器的人,这个库还允许转换多种格式的颜色:https: //tovic.github.io/color-picker/
CP.RGB2HEX([255, 255, 255])