使用javascript在html中使用线性渐变提供的范围中选择颜色 [英] pick color from a range provided by linear gradient in html using javascript

查看:110
本文介绍了使用javascript在html中使用线性渐变提供的范围中选择颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了线性渐变线性渐变(顶部,红色,黄色,绿色)。假设红色对应于0,绿色对应于1,我如何通过提供该范围内的数字来选择颜色,例如0.5应该对应于黄色,0.75 - 浅绿色,0.25 - 浅红色等。我想(0)是R(255)G(0)B(0)B(2) (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; //在渐变的第一部分,红色总是255
green =(inputValue * 2)* 255; //绿色从0增加到255
黄色= 0; //黄色总是0
} else {
red = 255 *(1 - ((inputValue - 0.5)* 2)); //在第二部分,红色从255到0
green = 255; //绿色始终为255
黄色= 0; //黄色总是0
}


I defined a linear gradient "linear-gradient(to top, red, yellow, green)". 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.

解决方案

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). Here you have actually 2 gradients, a first from red to yellow and a second from yellow to green. 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
}

这篇关于使用javascript在html中使用线性渐变提供的范围中选择颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆