Javascript 从绿色到红色取决于百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7128675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
from green to red color depend on percentage
提问by its me
I have a poll system and I want answers for this poll to be colored. For example: If it's 10% it would be red, if 40% it would be yellow and if 80% it would be green, so I want my javascript code to use the rgb colors to make a color according to the given percentage.
我有一个投票系统,我希望这个投票的答案是彩色的。例如:如果是 10% 则是红色,如果是 40% 则是黄色,如果是 80% 则是绿色,所以我希望我的 javascript 代码使用 rgb 颜色根据给定的百分比制作颜色。
function hexFromRGB(r, g, b) {
var hex = [
r.toString( 16 ),
g.toString( 16 ),
b.toString( 16 )
];
$.each( hex, function( nr, val ) {
if ( val.length === 1 ) {
hex[ nr ] = "0" + val;
}
});
return hex.join( "" ).toUpperCase();
}
Now I want hex from percent.
现在我想要百分比的十六进制。
回答by jongo45
A simple scheme using HSL along with fiddle:
使用 HSL 和小提琴的简单方案:
function getColor(value){
//value from 0 to 1
var hue=((1-value)*120).toString(10);
return ["hsl(",hue,",100%,50%)"].join("");
}
tweak saturation and luminosity as needed. and a fiddle.
根据需要调整饱和度和亮度。和一把小提琴。
function getColor(value) {
//value from 0 to 1
var hue = ((1 - value) * 120).toString(10);
return ["hsl(", hue, ",100%,50%)"].join("");
}
var len = 20;
for (var i = 0; i <= len; i++) {
var value = i / len;
var d = document.createElement('div');
d.textContent = "value=" + value;
d.style.backgroundColor = getColor(value);
document.body.appendChild(d);
}
回答by Jacob
This may be more than you need, but this lets you set up any arbitrary color map:
这可能超出您的需要,但这可以让您设置任意颜色映射:
var percentColors = [
{ pct: 0.0, color: { r: 0xff, g: 0x00, b: 0 } },
{ pct: 0.5, color: { r: 0xff, g: 0xff, b: 0 } },
{ pct: 1.0, color: { r: 0x00, g: 0xff, b: 0 } } ];
var getColorForPercentage = function(pct) {
for (var i = 1; i < percentColors.length - 1; i++) {
if (pct < percentColors[i].pct) {
break;
}
}
var lower = percentColors[i - 1];
var upper = percentColors[i];
var range = upper.pct - lower.pct;
var rangePct = (pct - lower.pct) / range;
var pctLower = 1 - rangePct;
var pctUpper = rangePct;
var color = {
r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
};
return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
// or output as hex if preferred
};
回答by Mattisdada
You can do this in a few lines of code (not including comments) without the need for any color maps.
您可以在几行代码(不包括注释)中完成此操作,而无需任何颜色映射。
function hsl_col_perc(percent, start, end) {
var a = percent / 100,
b = (end - start) * a,
c = b + start;
// Return a CSS HSL string
return 'hsl('+c+', 100%, 50%)';
}
//Change the start and end values to reflect the hue map
//Refernece : http://www.ncl.ucar.edu/Applications/Images/colormap_6_3_lg.png
/*
Quick ref:
0 – red
60 – yellow
120 – green
180 – turquoise
240 – blue
300 – pink
360 – red
*/
Example: https://jsfiddle.net/x363g1yc/634/
示例:https: //jsfiddle.net/x363g1yc/634/
No need for color maps (Unless it is a non-linear color change, which was not asked)
不需要颜色图(除非它是非线性的颜色变化,这没有被问到)
Warning: This is not compatible with IE8 or below. (Thanks Bernhard Fürst)
警告:这与 IE8 或更低版本不兼容。(感谢 Bernhard Fürst)
// Just used as a shortcut for below, completely optional
const red = 0,
yellow = 60,
green = 120,
turquoise = 180,
blue = 240,
pink = 300;
function hsl_col_perc(percent, start, end) {
var a = percent / 100,
b = (end - start) * a,
c = b + start;
// Return a CSS HSL string
return 'hsl(' + c + ', 100%, 50%)';
}
// Simple little animation
var percent = 0,
progressDiv = document.getElementById('progress'),
textDiv = document.getElementById('progress-text'),
progressContainerDiv = document.getElementById('progress-container')
function step(timestamp) {
percent = (percent < 100) ? percent + 0.5 : 0;
// Play with me!
let colour = hsl_col_perc(percent, red, green); //Red -> Green
progressDiv.style.backgroundColor = colour;
progressContainerDiv.style.borderColor = colour;
progressDiv.style.width = percent + '%';
textDiv.innerHTML = Math.floor(percent);
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
#progress {
width: 0%;
white-space: nowrap;
text-wrap: none;
height: 50px;
}
#progress-container {
border: solid 2px black;
width: 200px;
}
<h1 id="progress-text"></h1>
<div id="progress-container">
<div id="progress"></div>
</div>
回答by zmc
This method works well in this case (percent from 0 to 100):
这种方法在这种情况下效果很好(从 0 到 100 的百分比):
function getGreenToRed(percent){
r = percent<50 ? 255 : Math.floor(255-(percent*2-100)*255/100);
g = percent>50 ? 255 : Math.floor((percent*2)*255/100);
return 'rgb('+r+','+g+',0)';
}
回答by Joseph Marikle
function hexFromRGBPercent(r, g, b) {
var hex = [
Math.floor(r / 100 * 255).toString( 16 ),
Math.floor(g / 100 * 255).toString( 16 ),
Math.floor(b / 100 * 255).toString( 16 )
];
$.each( hex, function( nr, val ) {
if ( val.length === 1 ) {
hex[ nr ] = "0" + val;
}
});
return hex.join( "" ).toUpperCase();
}
Credit goes to andrew. He was faster.
归功于安德鲁。他更快。
回答by Aaron
Based on Jacobs answer I made a loadbar. This one is from green to red, but you can change the colors. For those interested here's my code and the jsfiddle ( http://jsfiddle.net/rxR3x/)
根据雅各布斯的回答,我做了一个负载条。这是从绿色到红色,但您可以更改颜色。对于那些感兴趣的人,这里是我的代码和 jsfiddle ( http://jsfiddle.net/rxR3x/)
var percentColors = [
{ pct: 0, color: '#00FF00' }, { pct: 3, color: '#12FF00' }, { pct: 6, color: '#24FF00' },
{ pct: 10, color: '#47FF00' }, { pct: 13, color: '#58FF00' }, { pct: 16, color: '#6AFF00' },
{ pct: 20, color: '#7CFF00' }, { pct: 23, color: '#8DFF00' }, { pct: 26, color: '#9FFF00' },
{ pct: 30, color: '#B0FF00' }, { pct: 33, color: '#C2FF00' }, { pct: 36, color: '#D4FF00' },
{ pct: 40, color: '#E5FF00' }, { pct: 43, color: '#F7FF00' }, { pct: 46, color: '#FFF600' },
{ pct: 50, color: '#FFE400' }, { pct: 53, color: '#FFD300' }, { pct: 56, color: '#FFC100' },
{ pct: 60, color: '#FFAF00' }, { pct: 63, color: '#FF9E00' }, { pct: 66, color: '#FF8C00' },
{ pct: 70, color: '#FF7B00' }, { pct: 73, color: '#FF6900' }, { pct: 76, color: '#FF5700' },
{ pct: 80, color: '#FF4600' }, { pct: 83, color: '#FF3400' }, { pct: 86, color: '#FF2300' },
{ pct: 90, color: '#FF1100' }, { pct: 93, color: '#FF0000' }, { pct: 96, color: '#FF0000' },
{ pct: 100, color: '#FF0000' }
];
var getColorPercent = function(selector, percent, time){
var i = 0;
var percentInterval = setInterval(function() {
i++;
if(percent >= percentColors[i].pct) {
console.log(percentColors[i].color);
$(selector).css('background-color', percentColors[i].color);
}
if(percentColors[i].pct>=percent) {
clearInterval(percentInterval);
}
}, time/25);
$(selector).animate({width:(200/100)*percent}, time);
}
getColorPercent('#loadbar_storage', 100, 1500);
var percentColors = [
{ pct: 0, color: '#00FF00' }, { pct: 3, color: '#12FF00' }, { pct: 6, color: '#24FF00' },
{ pct: 10, color: '#47FF00' }, { pct: 13, color: '#58FF00' }, { pct: 16, color: '#6AFF00' },
{ pct: 20, color: '#7CFF00' }, { pct: 23, color: '#8DFF00' }, { pct: 26, color: '#9FFF00' },
{ pct: 30, color: '#B0FF00' }, { pct: 33, color: '#C2FF00' }, { pct: 36, color: '#D4FF00' },
{ pct: 40, color: '#E5FF00' }, { pct: 43, color: '#F7FF00' }, { pct: 46, color: '#FFF600' },
{ pct: 50, color: '#FFE400' }, { pct: 53, color: '#FFD300' }, { pct: 56, color: '#FFC100' },
{ pct: 60, color: '#FFAF00' }, { pct: 63, color: '#FF9E00' }, { pct: 66, color: '#FF8C00' },
{ pct: 70, color: '#FF7B00' }, { pct: 73, color: '#FF6900' }, { pct: 76, color: '#FF5700' },
{ pct: 80, color: '#FF4600' }, { pct: 83, color: '#FF3400' }, { pct: 86, color: '#FF2300' },
{ pct: 90, color: '#FF1100' }, { pct: 93, color: '#FF0000' }, { pct: 96, color: '#FF0000' },
{ pct: 100, color: '#FF0000' }
];
var getColorPercent = function(selector, percent, time) {
var i = 0;
var percentInterval = setInterval(function() {
i++;
if (percent >= percentColors[i].pct) {
$(selector).css('background-color', percentColors[i].color);
}
if (percentColors[i].pct >= percent) {
clearInterval(percentInterval);
}
}, time / 25);
$(selector).animate({
width: (200 / 100) * percent
}, time);
}
getColorPercent('#loadbar', 100, 1500);
#loadbar_wrapper {
width: 200px;
height: 25px;
border: 1px solid #CECECE;
}
#loadbar {
width: 0px;
height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="loadbar_wrapper">
<div id="loadbar"></div>
</div>
回答by Rmaxx
I know this is originally an old javascript question, but I got here searching for CSS only solution, so maybe it will help others equally: It's actually quite simple:
我知道这最初是一个旧的 javascript 问题,但我在这里搜索仅使用CSS 的解决方案,所以也许它会同样帮助其他人:它实际上很简单:
Use the percentage as a HSL color value!
Red to Green spans H from 0
to 128
.(so you can pump the percentage up by 1.2
if you want). Example:
使用百分比作为 HSL 颜色值!红色到绿色跨度从 H0
到128
.(因此您可以根据需要提高百分比1.2
)。例子:
background-color:hsl(perc,100%,50%);
Where perc is just the number, without the %
sign.
其中 perc 只是数字,没有%
符号。
回答by keithxm23
This is what I came up with:
这就是我想出的:
function rgbify(maxval, minval, val, moreisgood) {
var intnsty = (val - minval) / (maxval - minval);
var r, g;
if (moreisgood) {
if (intnsty > 0.5) {
g = 255;
r = Math.round(2 * (1 - intnsty) * 255);
} else {
r = 255;
g = Math.round(2 * intnsty * 255);
}
} else { //lessisgood
if (intnsty > 0.5) {
r = 255;
g = Math.round(2 * (1 - intnsty) * 255);
} else {
g = 255;
r = Math.round(2 * intnsty * 255);
}
}
return "rgb(" + r.toString() + ", " + g.toString() + ", 0)";
}
The moreisgood
flag toggles if higher values should be red or green.
maxval
and minval
are the threshold values for your range.
val
is the value to be converted to rgb
moreisgood
如果较高的值应该是红色或绿色,则该标志会切换。
maxval
和minval
是您的范围的阈值。
val
是要转换为 rgb 的值
回答by Zeus
I know this is kind of bump to topic but I found one more way of doing it.
我知道这有点不合时宜,但我找到了另一种方法。
To do this you can also create a dynamic canvas of 100x1 dimension and apply gradient to it and then from function you just need to get pixel color of the percent location.
为此,您还可以创建一个 100x1 尺寸的动态画布并对其应用渐变,然后从函数中您只需要获取百分比位置的像素颜色。
Here is the code : This is global:
这是代码:这是全局的:
/* dynamic canvas */
// this should be done once in a page so out of function, makes function faster
var colorBook = $('<canvas />')[0];
colorBook.width = 101;
colorBook.height = 1;
var ctx = colorBook.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 101, 0);
grd.addColorStop(0, "rgb(255,0,0)"); //red
grd.addColorStop(0.5, "rgb(255,255,0)"); //yellow
grd.addColorStop(1, "rgb(0,255,0)"); //green
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 101, 1);
Then the function:
然后函数:
function getColor(value) {
return 'rgba(' + ctx.getImageData(Math.round(value), 0, 1, 1).data.join() + ')';
}
回答by fgfernandez0321
Changing from red
to green
color using HLS. The value should be from 0 to 100, in this case simulating percentage (%).
从更改red
到green
使用HLS颜色。该值应介于 0 到 100 之间,在本例中为模拟百分比 (%)。
function getColorFromRedToGreenByPercentage(value) {
const hue = Math.round(value);
return ["hsl(", hue, ", 50%, 50%)"].join("");
}