使用javascript从HTML中线性渐变提供的范围中选择颜色

pick color from a range provided by linear gradient in html using javascript

本文关键字:范围 颜色 选择 渐变 javascript HTML 线性 使用      更新时间:2023-09-26

我定义了一个线性渐变"linear-gradient(to top, red, yellow, green)"。假设红色对应0,绿色对应1,我如何通过提供该范围内的数字来选择颜色,例如0.5对应黄色,0.75对应浅绿色,0.25对应浅红色,等等。

基本上,您希望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)。这里实际上有两个梯度,第一个是从红色到黄色,第二个是从黄色到绿色。一个简单的方法是这样做,例如:

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;