簡體   English   中英

在javascript中將百分比轉換為顏色

[英]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';

}

更新:您更新了問題,但解決方案應該類似。

我的解決方案如下:

  1. 找出值 x 介於兩者之間(a,b = interval start and end)
  2. 獲取此區間(c1, c2)的顏色
  3. 找出 c1 和 c2 的紅綠藍值的差距(ex. r_gap = r2-r1)
  4. 計算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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM