Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an integer to a javascript color?

Tags:

javascript

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]);
like image 440
user1585020 Avatar asked Aug 08 '12 14:08

user1585020


People also ask

What is color code in JavaScript?

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.

How do you convert a number to an integer in JavaScript?

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.

What does integer mean in JavaScript?

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).


1 Answers

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/

like image 157
Esailija Avatar answered Sep 21 '22 15:09

Esailija