可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have an integer which I need to convert to a color in javascript. I am using an MVC model and am trying to replicate a model in a software for a web interface. I have the color in integer format from the database. It needs to be converted to a color in javascript.
For example: integers like -12525360, -5952982
I have the code like this :
items[x].barStyle = "stroke: Black; fill = Red";
So instead of giving the fill:Red, I need to give it the exact color corresponding to the integer value.
This is the code I have written in C#. I need the same thing in javascript. Here resourcecolor= the integer input.
var bytes = BitConverter.GetBytes(resourcecolor); ti.color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
回答1:
In javascript, you express a ARGB color that is to be used with canvas or css as a string like "rgba(0-255,0-255,0-255,0-1)".
You can convert the integer to that string format with this function:
function toColor(num) { num >>>= 0; var b = num & 0xFF, g = (num & 0xFF00) >>> 8, r = (num & 0xFF0000) >>> 16, a = ( (num & 0xFF000000) >>> 24 ) / 255 ; return "rgba(" + [r, g, b, a].join(",") + ")"; } toColor(-5952982) //"rgba(165,42,42,1)" toColor(-12525360) //"rgba(64,224,208,1)"
Demo: http://jsfiddle.net/Ectpk/
回答2:
Try:
hexColour = yourNumber.toString(16)
You may want to normalize 'yourNumber' too.
回答3:
Reading the comments on the question it seems you are able to manipulate the value on the server before its sent to the client. If you are using .NET I suggest using the ColorTranslator
int intColor = -12525360; string htmlColor = ColorTranslator.ToHtml(Color.FromArgb(intColor)); //#40E0D0
Or this (if you need the alpha channel):
int intColor = -12525360; Color c = Color.FromArgb(intColor); string htmlColor = String.Format(CultureInfo.InvariantCulture, "rgba({0},{1},{2},{3})", c.R, c.G, c.B, c.A / 255f);
回答4:
Disclosure: I'm the author of the library suggested below.
If you want to use a library rather than coding it yourself, the pusher.color Javascript library supports integer to HTML color conversions:
// Will set c to "rgba(105,80,131,1.0)" var c = pusher.color('packed_argb', -9875325).html()
Or if you wanted a different format:
var colorObject = pusher.color('packed_argb', -9875325); var htmlString = colorObject.html(); // i.e. "rgba(105,80,131,1.0)" var colorName = colorObject.html('keyword'); // closest named color var hexString = colorObject.html('hex6'); // "#695083"
Internally the library uses code very similar to Esailija's answer.