Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float values to a grayscale hex color value

this question is quick and simple.

I've a 2d array of floats ( 0,0000000 to 1,0000000 ) and i want to convert those numbers to a color value ( #000000 to #ffffff ).

note that i'm talking about just grayscale values.

0 = black | ... | 0.5 = middle gray | ... | 1 = white

does anyone know how to do that with javascript ? thx.

like image 479
Ace Avatar asked Apr 23 '13 21:04

Ace


1 Answers

Grayscale values in hex are those which got symmetrical distribution or Red, Green and Blue, e.g.: #111111, #5B5B5B, #A2A2A2.

To convert decimal number to hexadecial number you can use:

var number = 42;
var hex = Number(parseInt( number , 10)).toString(16);
hex // => "2a"

Put that to function:

function dec2hex(dec) {
    return Number(parseInt( dec , 10)).toString(16);
}

So your float can be converted to hex with:

var percentage = 0.4;
var color_part_dec = float * 255;
var color_part_hex = dec2hex( color_part_dec );
var color = "#" + color_part_hex + color_part_hex + color_part_hex;
color // => "#666666"

So your function will look like this:

function float2color( percentage ) {
    var color_part_dec = 255 * percentage;
    var color_part_hex = Number(parseInt( color_part_dec , 10)).toString(16);
    return "#" + color_part_hex + color_part_hex + color_part_hex;
}
like image 138
chrmod Avatar answered Oct 27 '22 00:10

chrmod