79128643

Date: 2024-10-26 13:38:37
Score: 3.5
Natty:
Report link

I was recently facing a similar issue where I needed to extract an exact HEX color value. While a masked gradient worked somewhat fine as well, it had some implications on rendering quality and performance.

Here's the helper function I've written to get the color value by percentage from the defined gradient (supports multiple color stops):

function getGradientColor(colors, percentage) {
  percentage = Math.max(0, Math.min(100, percentage));
  
  if (colors.length === 1) return colors[0];
  
  const index = (colors.length - 1) * percentage / 100;
  const i = Math.floor(index);
  const t = index - i;
  
  const color1 = colors[i];
  const color2 = colors[Math.min(i + 1, colors.length - 1)];
  
  const rgb = [0, 1, 2].map(j => {
    const c1 = parseInt(color1.slice(1 + j * 2, 3 + j * 2), 16);
    const c2 = parseInt(color2.slice(1 + j * 2, 3 + j * 2), 16);
    return Math.round(c1 * (1 - t) + c2 * t);
  });
  
  return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('');
}

I've described the thought process a bit futher in this article: https://ivomynttinen.com/blog/get-a-color-value-by-percentage-from-gradient/

Reasons:
  • Blacklisted phrase (1): this article
  • Blacklisted phrase (0.5): I need
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): facing a similar issue
  • Low reputation (1):
Posted by: Ivo Mynttinen