gpt4 book ai didi

javascript - 颜色图在 100% 的情况下不起作用

转载 作者:行者123 更新时间:2023-11-28 21:17:46 25 4
gpt4 key购买 nike

我有这个很棒的代码

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 = 0; i < percentColors.length; i++) {
if (pct < percentColors[i].pct) {
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
}
}
}

当我使用它时

alert(getColorForPercentage(90/100));//red

alert(getColorForPercentage(0/100));//green

但是当

alert(getColorForPercentage(100/100));

它应该给出全红色,但它给我未定义

最佳答案

更改:

if (pct < percentColors[i].pct) {

if (pct <= percentColors[i].pct) {

因为代码是 1 < 1.0 // false

替换你的for语句,关键更改:var lower = percentColors[i - 1] || {pct:0};

for (var i = 0; i < percentColors.length; i++) {
if (pct <= percentColors[i].pct) {
var lower = percentColors[i - 1] || { pct: 0.1, color: { r: 0x0, g: 0x00, b: 0 } };
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
}
}

关于javascript - 颜色图在 100% 的情况下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7195349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com