AFAIK you cannot read a value off from a gradient as the gradient object do not expose methods to do so.
You can however create an off-screen canvas, draw a gradient and read the pixel value from there.
For example, lets create an object GradientReader. This allows us to instantiate it and embed methods and so forth:
function GradientReader(colorStops) {
const canvas = document.createElement('canvas'); // create canvas element
const ctx = canvas.getContext('2d'); // get context
const gr = ctx.createLinearGradient(0, 0, 101, 0); // create a gradient
canvas.width = 101; // 101 pixels incl.
canvas.height = 1; // as the gradient
for (const { stop, color } of colorStops) { // add color stops
gr.addColorStop(stop, color);
}
ctx.fillStyle = gr; // set as fill style
ctx.fillRect(0, 0, 101, 1); // draw a single line
// method to get color of gradient at % position [0, 100]
return {
getColor: (pst) => ctx.getImageData(pst|0, 0, 1, 1).data
};
}
Now we can setup the object with the color stops.
const gr = new GradientReader([{stop: 0.0, color: '#f00'},
{stop: 0.5, color: '#ff0'},
{stop: 1.0, color: 'rgb(79,189,0)'}]);
We now have an object which mimics the gradient and all we need to do now is to call its method getColor()
with a percentage value:
const col = gr.getColor(pst);
el.style.backgroundColor = `rgb(${col[0]}, ${col[1]}, ${col[2]})`;
Modify to your liking/needs.
Hope this helps!