Cyclone
Cyclone

Reputation: 18295

Javascript hex number interpolation between several numbers

I'm creating a "characters remaining" type counter for a site of mine, and am trying to get smooth color transitions.

How would I go about creating a function to obtain the hex value for a color if I pass the maximum number (in this case 300) and the current char count assuming the pattern is green, yellow, orange, red?

This is in Javascript. Here is what I have so far:

function commentcounter(val) {
max = 300;
if(val >= max){
    color = '#FF0000';
}else if(val > (max / 2)){
    color = '#FF9900';
}else{
    color = '#00FF00';
}
display = '<span style="color:' + color + '">' + val + '/' + max + '</span>';
document.getElementById('counter').innerHTML = display;
}

As you can see, this doesn't really interpolate, just goes from green to orange to red.

Upvotes: 3

Views: 1472

Answers (3)

John Stimac
John Stimac

Reputation: 5491

"rgb("+Math.round(Math.min((((chars+(max/2))*2/max)-1)*255,255))+","+Math.round(Math.min(((chars*-2/max)+2)*255,255))+",0)";

Upvotes: 1

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

This worked better than rgb() for me:

var pct = val / max;
var h = pct * 120;
var newColor = 'hsl(' + h + ', 80%, 50%)';

http://jsfiddle.net/ehUHp/

Upvotes: 0

SLaks
SLaks

Reputation: 887469

You need to interpolate each color component individually from 0 to 255 (or vice-versa).
This will be much easier if you use color: rgb(0, 255, 0).

Upvotes: 5

Related Questions