js計算線性漸變的中間顏色值

carol2014發表於2024-03-28

可能會使用js計算線性漸變的中間顏色值,寫個demo記錄下

<style>
  #colors {
    margin-top: 2rem;
    display: flex;
  }
  #colors div {
    width: 100px;
    height: 100px;
  }
</style>
<div id="colors">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<script>
  // RGB轉16進位制色值
  function rgbToHex(red, green, blue) {
    const toHex = (colorValue) => {
      const hex = colorValue.toString(16);
      return hex.length == 1 ? "0" + hex : hex;
    };
    return "#" + toHex(red) + toHex(green) + toHex(blue);
  }

  // 16進位制色值轉RGB
  function hexToRgb(hex) {
    hex = hex.replace(/^\s*#|\s*$/g, "");
    let red = parseInt(hex.substr(0, 2), 16);
    let green = parseInt(hex.substr(2, 2), 16);
    let blue = parseInt(hex.substr(4, 2), 16);

    return [red, green, blue];
  }

  //計算線性漸變的中間顏色值
  function getColorBetweenTwoColors(colorA_str, colorB_str, ratio) {
    const colorA = hexToRgb(colorA_str);
    const colorB = hexToRgb(colorB_str);
    const r = Math.round((colorB[0] - colorA[0]) * ratio + colorA[0]);
    const g = Math.round((colorB[1] - colorA[1]) * ratio + colorA[1]);
    const b = Math.round((colorB[2] - colorA[2]) * ratio + colorA[2]);

    return rgbToHex(r, g, b);
  }

  const colorA = "#FF0000"; //紅色
  const colorB = "#00FF00"; //綠色

  const radio_arr = [0, 0.25, 0.5, 0.75, 1];
  const elems = document.querySelectorAll(`#colors div`);
  for (let i in radio_arr) {
    elems[i].style.backgroundColor = getColorBetweenTwoColors(colorA, colorB, radio_arr[i]);
  }
</script>

js計算線性漸變的中間顏色值

相關文章