简体   繁体   English

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

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

I defined a linear gradient "linear-gradient(to top, red, yellow, green)". 我定义了一个线性渐变“ linear-gradient(顶部,红色,黄色,绿色)”。 Let's say that red corresponds to 0 and green corresponds to 1, how can I pick a color by providing number in that range, for example 0.5 should correspond to yellow, 0.75 - light green, 0.25 - light red, etc. I would like to present it as javascript function. 假设红色对应于0,绿色对应于1,我如何通过提供该范围内的数字来选择颜色,例如0.5应该对应于黄色,0.75-浅绿色,0.25-浅红色等。我想呈现为javascript函数。

Basically, you want f(0) to be R(255) G(0) B(0), f(1/2) to be R(255) G(255) B(0) and finally f(1) to be R(0) G(255) B(0). 基本上,您希望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)。 Here you have actually 2 gradients, a first from red to yellow and a second from yellow to green. 在这里,您实际上有2个渐变,第一个从红色到黄色,第二个从黄色到绿色。 A simple way to do that would be to say for instance : 一个简单的方法就是例如:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM