Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
Carl

convert hexadecimal number color values to strings for css

Recommended Posts

I was recently converting a Flash project over to JS.

This project involves colorizing objects based on Kuler Themes.

 

Sample of the js version: http://snorkl.tv/dev/kulerLooper/

 

In ActionScript I stored my color values in a massive array like this:

 

 

var kulers:Array = [
[0x468966, 0xFFF0A5, 0xFFB03B, 0xB64926, 0x8E2800],
[0x2E0927, 0xD90000, 0xFF2D00, 0xFF8C00, 0x04756F],
[0x96CA2D, 0xB5E655, 0xEDF7F2, 0x4BB5C1, 0x7FC6BC],
[0x225378, 0x1695A3, 0xACF0F2, 0xF3FFE2, 0xEB7F00],
[0xFFD393, 0x9C9B7A, 0xFFD393, 0xFF974F, 0xF54F29],
[0xF54F29, 0x1F8A70, 0xBEDB39, 0xFFE11A, 0xFD7400]
]

 

For people who have used Flash, the preceeding 0x will be familiar for hex numbers.

With css we need our colors formatted as strings "#FF0000" with the pound sign

 

Once I copied my array into my js file I realized that the formatting didn't work with css.

My array has literally hundreds of color values and I needed an easy way to convert them.

 

Just incase anyone finds themselves in a similar boat, I came across a color conversion function on stackoverflow : http://stackoverflow...ings-vice-versa which I trimmed down to the core functionality that I needed:

 

function parseColor(color) {

if (typeof color === 'number') {
	//make sure our hexadecimal number is padded out
	color = '#' + ('00000' + (color | 0).toString(16)).substr(-6);
}

return color;

};

 

to convert 0xFF000 to "#FF0000" simply do:

 

parseColor(0xFF000);  // returns "#FF0000";

 

I'm wondering if it makes sense to have the CSSPlugin detect 0x numbers and do the conversion behind the scenes? Or is it too much of an edge-case?

 

Either way, I hope others will find the function above helpful.

 

-Carl

  • Like 1
Link to comment
Share on other sites

You could just search/replace "#" for "0x" in your original code, although I guess you'd also need to surround the values in quotes. I can see the benefit of having CSSPlugin recognize those numeric values so I just posted a new version of CSSPlugin that should do it. Vwalla! Giver 'er a shot.

Link to comment
Share on other sites

yeah, after doing the find/replace surrounding the values in quotes was the troublesome part. Thanks for adding this feature. It worked great in my tests.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×