Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number between 1 and 16777215 to a colour value

Tags:

javascript

I'm trying to convert a number between 1 and 16,777,215 to any colour format (RGB/HSL/HEX) that increments through the colour spectrum using Javascript/jQuery.

The number 16,777,215 is the total possible combinations of RGB(255,255,255) which is 32 bit colour.

I initially thought converting the value to a hex value using toString(16) would increment through the spectrum, however as the number increases it seems to work through different lightness values instead and flashes. An example of this unwanted behaviour is here http://jsfiddle.net/2z82auka/

var colour = 16777215;
window.setInterval(function(){
    colour -= 1000;
    $('body').css({background:'#' + colour.toString(16)});
}, 50);

How can I convert a value between 1 and 16777215 to a colour on the colour spectrum shown below?

Wanted outcome

like image 890
CMYJ Avatar asked Apr 24 '15 15:04

CMYJ


Video Answer


2 Answers

The code below will do exactly what you want - it'll give you vibrant colors of the color spectrum exactly as the image below, and to prove it, the demo will print out the integer values beside the color. The result will look like this. Please use the rainbow function in your setInterval code.

spectrum

var colours = 16777215;

function rainbow(numOfSteps, step) {
	var r, g, b;
	var h = 1 - (step / numOfSteps);
	var i = ~~(h * 6);
	var f = h * 6 - i;
	var q = 1 - f;
	switch(i % 6){
		case 0: r = 1, g = f, b = 0; break;
		case 1: r = q, g = 1, b = 0; break;
		case 2: r = 0, g = 1, b = f; break;
		case 3: r = 0, g = q, b = 1; break;
		case 4: r = f, g = 0, b = 1; break;
		case 5: r = 1, g = 0, b = q; break;
	}
	var c = "#" + ("00" + (~ ~(r * 235)).toString(16)).slice(-2) + ("00" + (~ ~(g * 235)).toString(16)).slice(-2) + ("00" + (~ ~(b * 235)).toString(16)).slice(-2);
	return (c);
}

function render(i) {
	var item = "<li style='background-color:" + rainbow(colours, i) + "'>" + i + "</li>";
	$("ul").append(item);
}

function repeat(fn, times) {
	for (var i = 0; i < times; i+=10000) fn(i);
}

repeat(render, colours);
li {
  font-size:8px;
  height:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul></ul>

(I can't take credit for this code, but I can take credit for not giving up and settling for jerky color changes. Ref: https://gist.github.com/ruiwen/6163115)

like image 167
Drakes Avatar answered Nov 02 '22 22:11

Drakes


Convert to range the initial value from 1 > 16777216 from 0 > 360

Technique here: Convert a number range to another range, maintaining ratio

Then use the HSL colour model, and increment from H0 S100 L100 > H360 S100 L100

like image 28
Jack Wild Avatar answered Nov 02 '22 22:11

Jack Wild