从渐变区间中插值取出对应值的颜色

//从渐变区间中插值取出对应的颜色   颜色数组  颜色对应值数组   想要插值颜色的数值
export function selectColor(gradientColors,gradientValues,valueToMatch){
  //插值计算
  function interpolateColor(color1, color2, percentage) {
      const r1 = parseInt(color1.slice(1, 3), 16);
      const g1 = parseInt(color1.slice(3, 5), 16);
      const b1 = parseInt(color1.slice(5, 7), 16);

      const r2 = parseInt(color2.slice(1, 3), 16);
      const g2 = parseInt(color2.slice(3, 5), 16);
      const b2 = parseInt(color2.slice(5, 7), 16);

      const r = Math.round(r1 + (r2 - r1) * percentage);
      const g = Math.round(g1 + (g2 - g1) * percentage);
      const b = Math.round(b1 + (b2 - b1) * percentage);

      return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
  }
  let color = '';

  for (let i = 1; i < gradientValues.length; i++) {
      //寻找目标值在那一个渐变区间
      if (valueToMatch <= gradientValues[i]) {
          //计算比例  上区间和下区间的比例
          const percentage = (valueToMatch - gradientValues[i - 1]) / (gradientValues[i] - gradientValues[i - 1]);
          color = interpolateColor(gradientColors[i - 1], gradientColors[i], percentage);
          break;
      }
  }
  // console.log(color)
  return color
}

你可能感兴趣的:(html,前端,javascript)