指定された数値に従って色の値を計算したいと思います。
0 -> pure red
100 -> pure green
example: 75 -> color, which is 75% from red to green.
有効期限カウンターにこれが必要です。これは、日数のカウントダウンに応じて適切な色を示します。
指定された数値に従って色の値を計算したいと思います。
0 -> pure red
100 -> pure green
example: 75 -> color, which is 75% from red to green.
有効期限カウンターにこれが必要です。これは、日数のカウントダウンに応じて適切な色を示します。
ペバラの答えは素晴らしいです。私は彼の jsfiddle を私のニーズに合わせましたが、他の人にも役立つかもしれません: http://jsfiddle.net/rE6Rk/8/
色の不均一な分布を可能にします。私の場合、0.5 (50) 未満のものはすべて赤くしたかったのです。0.75 は赤と緑の中間になります。したがって、ハード ボーダー 0 と 1 を使用する代わりに、両方をシフトすることができます。
変更は numberToColorHsl() 関数のみにあります: * i は int 0-100 ではなく浮動小数点 0-1 です * 追加のパラメータ min/max
/**
* Convert a number to a color using hsl, with range definition.
* Example: if min/max are 0/1, and i is 0.75, the color is closer to green.
* Example: if min/max are 0.5/1, and i is 0.75, the color is in the middle between red and green.
* @param i (floating point, range 0 to 1)
* param min (floating point, range 0 to 1, all i at and below this is red)
* param max (floating point, range 0 to 1, all i at and above this is green)
*/
function numberToColorHsl(i, min, max) {
var ratio = i;
if (min> 0 || max < 1) {
if (i < min) {
ratio = 0;
} else if (i > max) {
ratio = 1;
} else {
var range = max - min;
ratio = (i-min) / range;
}
}
// as the function expects a value between 0 and 1, and red = 0° and green = 120°
// we convert the input to the appropriate hue value
var hue = ratio * 1.2 / 3.60;
//if (minMaxFactor!=1) hue /= minMaxFactor;
//console.log(hue);
// we convert hsl to rgb (saturation 100%, lightness 50%)
var rgb = hslToRgb(hue, 1, .5);
// we format to css value and return
return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
}
ビジュアルは言葉よりもよく説明します。
これは単純な計算です ;)
Red = 255 - (255 * (Number / 100))
Green = 255 * (Number / 100)
Blue = 0
それで全部です。