开发者

colour range in javascript

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 -= M开发者_如何学Cath.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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜