Given a string of a valid CSS color value:
- #fff
- #ffffff
- white
- rgb(255, 255, 255)
Need to get an array of numbers of the following format: [R, G, B]
What is the most efficient way of doing this in JavaScript (assuming a major browser)?
Given a string of a valid CSS color value:
Need to get an array of numbers of the following format: [R, G, B]
What is the most efficient way of doing this in JavaScript (assuming a major browser)?
Quicker and more efficient way
In addition to @NiettheDarkAbsol 's correct answer, there are some aspects:
backgroundColor could be
rgb( 3 values )
orrgba( 4 values)
match
function is nice but using regular expression is expensive! Whenever possible, prefersplit
instead.This function is simplier and quicker:
Ok returned values are still strings, and they contains unwanted spaces, but if used in mathematical expression, they would work correctly!
At all I prefer this anyway: They may be included as is:
Support
#RnGnBn
format, for IEx as commented by Emile BergeronThere is a small and quick function working with
rgb(r,g,b)
,#RGB
,#RRGGBB
and#RRRGGGBBB
:Demo
// This will return a [red.green,blue] decimal array for the samples you posted, plus rgb percentages.
// It ignores transparency, hsl and the extended set of color names most browsers support:
//This version will return a [red.green,blue] decimal array for most color strings, ignoring transparency.
Necromancing.
For anybody that actually needs it, here's fully working and feature-complete code.
Think of it as complement to the answer of "Niet the Dark Absol"
Cheers.
For both type of colors hsl and rgb this works:
Obviously, the numeric values will be easier to parse than names. So we do those first.
That's one. Now for the full six-digit format:
And now for
rgb()
format:Optionally, you can also add support for
rgba
format, and evenhsl
/hsla
if you add an HSL2RGB conversion function.Finally, the named colours.
And close the function:
Actually, I don't know why I bothered writing all that. I just noticed you specified "assuming a major browser", I'm assuming that also means "up-to-date"? If so...
An up-to-date browser will convert any given colour to
rgb()
format in its computed style. Just get it back, and read it out.For HTML5 compatible browsers I write a single pixel into a
<canvas>
using the specified value, and read back thergba
quad.For performance I memoize this function so that repeated calls for the same colour string don't have to perform the canvas operations.
EDIT updated for ES6 and to remove jQuery dependency
EDIT (1j01) added invalid color detection, and a function that supports passing a fallback color