[英]Convert percentage to colors in javascript
我想根據從 -1 到 1 的值生成顏色
基色是
我的差距是 H:0 =1, H:60 = 0.5, H:170= 0, H:200= -1 ( S:100 and L:50 )
我找到了一個將百分比從綠色轉換為紅色的示例。
function percentageToColor(percentage, maxHue = 200, minHue = 0) {
const hue = percentage * (maxHue - minHue) + minHue;
return `hsl(${hue}, 100%, 50%)`;
}
我想通過添加藍色和使用從 -1 到 1 的值來適應我的情況,方法是尊重我上面提到的間隙等價,但我不知道該怎么做。
更新
我想使用 HSL/HSV
我正在尋找一種方法來找到百分比和H
值之間的關系
更新 2
我已經實施了@Muhammed B. Aydemir 解決方案,但在視覺上我得到了光譜的顏色(最終是黑色)
percentageToColor(pourcentage) {
let x = pourcentage.toFixed(2);
const colors = [[4, 189, 237], [10, 19, 0], [255, 248, 3], [253, 45, 45]];
const range = [0, 1, 1.5, 2];
const inBetween = (x, a, b) => x >= a && x <= b;
for (let i = 0; i < range.length; i++) {
const m = range[i];
const n = range[i + 1];
console.log(inBetween(x, m, n));
if (inBetween(x, m, n)) {
const c1 = colors[i];
const c2 = colors[i + 1];
const rangeDiff = n - m;
const ratio = Math.abs((x - m) / rangeDiff);
const [r, g, b] = c1.map((e, i) => {
const e1 = c1[i];
const e2 = c2[i];
return Math.round(e1 + (e2 - e1) * ratio);
});
let color = [r, g, b].reduce((p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '#');
console.log([x, color]);
return color;
} else if (x > range[range.length - 1]) {
console.log(x + 'red');
return 'red';
}
}
return 'OUT OF RANGE';
}
更新:您更新了問題,但解決方案應該類似。
我的解決方案如下:
(a,b = interval start and end)
(c1, c2)
的顏色(ex. r_gap = r2-r1)
r = r1 + r_gap * |x - a / interval_length|
你應該有你的r,g,b
值。
例子:
const colors = [[4, 189, 237], [99, 19, 0], [255, 248, 3], [253, 45, 45]] const range = [-1, 0, 0.5, 1] const inBetween = (x, a, b) => x >= a && x <= b const toRGB = x => { for (let i = 0; i < range.length; i++) { const m = range[i] const n = range[i + 1] if (inBetween(x, m, n)) { const c1 = colors[i] const c2 = colors[i + 1] const rangeDiff = n - m const ratio = Math.abs((x - m) / rangeDiff) const [r, g, b] = c1.map((e, i) => { const e1 = c1[i] const e2 = c2[i] return Math.round(e1 + (e2 - e1) * ratio) }) console.log(r, g, b) return [r, g, b].reduce((p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '#') } } if (x < range[0]) return 'white' // below range return 'red' // above range } const element = document.createElement('div'); let linearGradient = '' for (let i = range[0]; i < range[range.length - 1]; i += 0.01) linearGradient += toRGB(i) + ',' element.style.backgroundImage = `linear-gradient(to right,${linearGradient}${toRGB(range[range.length -1])})`; document.body.append(element);
div { width: 500px; height: 40px; float: left; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.