【发布时间】:2014-08-05 17:00:42
【问题描述】:
我定义了一个线性渐变“线性渐变(到顶部,红色,黄色,绿色)”。假设红色对应0,绿色对应1,我如何通过提供该范围内的数字来选择颜色,例如0.5应该对应黄色,0.75 - 浅绿色,0.25 - 浅红色等。我想将其呈现为 javascript 函数。
【问题讨论】:
标签: javascript html colors gradient
我定义了一个线性渐变“线性渐变(到顶部,红色,黄色,绿色)”。假设红色对应0,绿色对应1,我如何通过提供该范围内的数字来选择颜色,例如0.5应该对应黄色,0.75 - 浅绿色,0.25 - 浅红色等。我想将其呈现为 javascript 函数。
【问题讨论】:
标签: javascript html colors gradient
基本上,您希望 f(0) 为 R(255) G(0) B(0),f(1/2) 为 R(255) G(255) B(0),最后 f( 1) 为 R(0) G(255) B(0)。 这里实际上有 2 个渐变,第一个从红色到黄色,第二个从黄色到绿色。 一个简单的方法是说例如:
if(inputValue < 0.5){
red = 255; //On first part of the gradient, red is always 255
green = (inputValue * 2) * 255; //Green increase from 0 to 255
yellow = 0; //Yellow is always 0
}else{
red = 255*(1-((inputValue - 0.5)*2)); //On that second part, red go from 255 to 0
green = 255; //Green is always 255
yellow = 0; //Yellow is always 0
}
【讨论】:
var output.r = (inputValue * color1.r + (1 - inputValue) * color2.r) / 2;
var output.g = (inputValue * color1.g + (1 - inputValue) * color2.g) / 2;
var output.b = (inputValue * color1.b + (1 - inputValue) * color2.b) / 2;
【讨论】: