Assign Color

mail@pastecode.io avatar
unknown
javascript
2 years ago
762 B
1
Indexable
Never
function getColor(value, start, end, startColor, endColor) {
  // Normalize the value to a range between 0 and 1
  let normalizedValue = (value - start) / (end - start);

  // Interpolate the colors based on the normalized value
  let color = interpolateColors(startColor, endColor, normalizedValue);

  return color;
}

function interpolateColors(color1, color2, factor) {
  if (arguments.length < 3) factor = 0.5;
  let result = color1.slice();
  for (let i=0;i<3;i++) {
    result[i] = Math.round(result[i] + factor*(color2[i]-color1[i]));
  }
  return result;
}

// Example usage
let startColor = [255, 0, 0]; // Red
let endColor = [0, 0, 255]; // Blue
let color = getColor(50, 0, 100, startColor, endColor); // Returns a color halfway between red and blue