Home  >  Article  >  Web Front-end  >  Another gradient color generation algorithm_html/css_WEB-ITnose

Another gradient color generation algorithm_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:44:461196browse

Background

Simplified the background. Given an indicator X, it is normal when it is relatively small, and it is dangerous when it is relatively large. In order to display it more intuitively, I want to use color to highlight this value when it is displayed on the front end? When it is small, the color is green, when it is large, it is red, and some yellow is used for transition.

I searched on google and couldn’t find the appropriate code. Ever since, Luzhu planned to make one~ It’s so funny...

Analysis

Color can be represented by RGB values ​​in HTML?? Green is rgb(0,255,0), red is rgb(255,0, 0), yellow is rgb(255,255,0). In order to achieve the gradient effect, you need to design a function F:

F(0) = rgb(0,255,0);F(比较大的值) = rgb(255,0,0);F(中间的值) = rgb(255,255,0);

As a result, the

function seems to be very complicated. But it came out after adjusting it for a while, and the effect was pretty good.

Share the code:

/** * 生成渐变色,从绿色到红色的渐变 * @param int   $x          指标值 * @param int   $threshold  渐变阈值,$x等于这个值的时候刚好是黄色 * @param float $brightness 亮度,从0到1 * @return string RGB格式的颜色值 */function generateGradientColor($x, $threshold, $brightness = 1){    return sprintf('rgb(%d, %d, 0)',                    intval(min(255, ($x * 1.0 / $threshold * 255)) * $brightness),                    intval(max(0, min(255, (2 - $x * 1.0 / $threshold) * 255)) * $brightness));}

Effect

The effect of the gradient color generated is as follows (threshold = 25):

 

Attached is the PHP code that generates the above effects:

<style>    div{        display: block;        font-size: 10px;        height: 1em;    }</style><?phpfor ($i = 1; $i < 50; $i++){    echo strtr("<div style='width: {width}em; background-color: {color}'>$i</div>", array(        '{width}' => $i,        '{color}' => generateGradientColor($i, 25)    ));}?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn