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

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

问题描述

我正在使用 Javascript 和 Canvas 制作绘画应用程序,并使用这种格式的字符串来指定所选颜色:

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)"

因为画布上下文的 fillStyle 属性接受该格式的字符串.

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

然而,我现在需要从这个字符串中获取单独的组件,并且想知道是否有一种方法可以在不进行乱七八糟的字符串操作的情况下做到这一点.可能是某种内置方式将该字符串转换为某种颜色对象,然后访问其 r、g 和 b 组件?

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?

谢谢.

推荐答案

注意 - 我们都支持正则表达式吃我的脑子和踢我的狗的态度,但正则表达式版本似乎是更好的方法.我的看法.看看吧.

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.

非正则表达式方法:

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"]

或者...一个非常简单的正则表达式:

Or... A really simple regex:

哎呀,由于某种原因,在正则表达式中有一个 i.

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天全站免登陆