从Javascript中的rgb字符串获取颜色组件? [英] Get a color component from an rgb string in Javascript?

查看:109
本文介绍了从Javascript中的rgb字符串获取颜色组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Javascript和Canvas制作绘画应用程序,并以此格式使用字符串指定所选颜色:

rgb (255,0,0)



因为canvas上下文fillStyle属性接受这种格式的字符串。



然而,我现在需要从这个字符串中获取单个组件,并且想知道是否有一种方法可以做到这一点,而不会出现混乱的字符串操作。可能有些内置方法可以将字符串转换为一种颜色对象,然后访问它的r,g和b组件?



谢谢。

解决方案

注意 - 我们都在使用正则表达式吃掉了我的大脑并且踢了我的狗态度,但正则表达式似乎是更好的方法。我的想法。检查它。



非正则表达式方法:

  var rgb ='rgb(200,12,53)'; 

rgb = rgb.substring(4,rgb.length-1)
.replace(/ / g,'')
.split(',');

console.log(rgb);

http://jsfiddle.net/userdude/Fg9Ba/



输出:

  [200,12,53] 



<编辑:Ooops,在正则表达式中有一个 i 某些原因。

  var rgb ='rgb(200,12,53)'; 

rgb = rgb.replace(/ [^ \d,] / g,'').split(',');

console.log(rgb);

http://jsfiddle.net/userdude/Fg9Ba/2


I'm using Javascript and Canvas to make a painting app and was using strings in this format to designate chosen colors:

"rgb(255,0,0)"

Because the canvas context fillStyle property takes in strings of that format.

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?

Thanks.

解决方案

NOTE - We're all on board with the regex ate my brains and kicked my dog attitude, 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/

Outputs:

["200", "12", "53"]

Or... A really simple regex:

EDIT: Ooops, had an i in the regex for some reason.

var rgb = 'rgb(200, 12, 53)';

rgb = rgb.replace(/[^\d,]/g, '').split(',');

console.log(rgb);

http://jsfiddle.net/userdude/Fg9Ba/2

这篇关于从Javascript中的rgb字符串获取颜色组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆