Is there a built-in function that would convert a color by name into its hex representation? Like I want to pass 'white' and receive '#FFFFFF'. I really want to avoid coding all hundred if's myself :)
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
@dlauzon suggested I convert my comment into an answer. Thanks for suggesting! Here it is :)
building on Greg's answer including gray/gray version
added: flag to pass through unresolved strings
available as gist colorhelpersforcanvas.js
some test cases:
as a bonus here my use case for that in a color-string to color-string-with-alpha conversion:
works with any css defined color including: rgba, rgb, r%g%b%, #rgb, #rrggbb, hsl, hsla
mostly useful in drawing with alpha/opacity/transparency onto a HTML5 canvas element with passed on color strings
test:
This will give it to you in RGB - you should be able to do the hex conversion pretty easily.
Get Computed style is not supported on all browsers.
Here's an all purpose solution that does exactly what you want in every browser that is 100% programmatic, goodbye giant static table of names and hex values!:
A more complete explanation and live example can be found here: http://www.backalleycoder.com/2010/10/05/converting-css-named-colors-to-rgb-and-hex/
Here function where you use the browser to calculate it for you
Explanation by line:
credits to zyklus for his rgb to hex code
You'll need to rely on
getComputedStyle(...)
.Example of using
getComputedStyle
:And to convert "rgb(R, G, B)" to #RRGGBB you can use: