colour range in javascript

2019-08-04 07:28发布

Using JavaScript, if I've got a low integer, and a high integer, and I wanted to work out a range of HEX colours, to represent the different vlues within that range... what would be the best way of doing it?

I can give an example:

// calculate total value
var total = 0;
for( d in data ){
  total += data[d].value;
}

// Our main color
var r=150,g=200,b=250,

// some color calculations based on value and total value

val = (data[iso].value/total)*35;

r -= Math.round(val*30);
g -= Math.round(val*30);
b -= Math.round(val*30);

This code is currently trying to create a range of colours, but it falls down where a very high number is passed to it, as it goes below 0 for each of r, g, and b, causing it to be no good for colour purposes... if you see what I mean?

Can anyone suggest a better way? Thank you.

1条回答
戒情不戒烟
2楼-- · 2019-08-04 08:30

Normalize your input to the [0,1] range, then use that value to interpolate between two valid colors.

var norm = (value - minimum) / (maximum - minimum);
r = Math.round(norm * minRed   + (1 - norm) * maxRed);
g = Math.round(norm * minGreen + (1 - norm) * maxGreen);
b = Math.round(norm * minBlue  + (1 - norm) * maxBlue);
查看更多
登录 后发表回答