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/