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]);
Colors are typically expressed through hexadecimal codes, either prefixed using a pound sign ( # ) or 0x to denote base 16 values. Combining these channels together, we end up with RGB codes, such as: 0xff0000 — Red. 0x00ff00 — Green.
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
In JavaScript, all numbers are floating point. Integers are floating-point numbers without a fraction. Converting a number n to an integer means finding the integer that is “closest” to n (where the meaning of “closest” depends on how you convert).
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With