I have the following data structure that will paint a gradient in a canvas:
{
id: 'gold',
degree: 133,
colorStops: [
[0, 'rgba(0,0,0,1)'],
[0.09, 'rgba(48,37,27,1)'],
[0.19, 'rgba(95,77,59,1)'],
[0.50, 'rgba(223,223,223,1)'],
[0.77, 'rgba(95,77,59,1)'],
[0.94, 'rgba(48,37,27,1)'],
[1, 'rgba(0,0,0,1)'],
]
},
I’m trying to create a function that gets as an input the data above and draws the gradient on the canvas.
I get an angle in degrees and I would like to be able to calculate x1 and y1
to use in createLineGradient. I have used the laws of sines but I’m not understanding where I went wrong to calculate the x1 and y1
positions:
function calculateX1Y1(angleDegree: number, x0: number, y0: number, canvaWidth: number) {
const angleRadians = angleDegree * Math.PI / 180;
let _x1 = canvaWidth * Math.cos(angleRadians);
let _y1 = canvaWidth * Math.sin(angleRadians);
return { _x1, _y1 };
}
export function paintGradient(
canva: HTMLCanvasElement,
gradient: GRADIENT_PAYLOAD,
canvaWidth: number,
canvaHeight: number,
) {
const ctx = canva.getContext('2d')!;
const x0 = 0;
const y0 = 0;
const {_x1, _y1} = calculateX1Y1(gradient.degree, x0, y0, canvaWidth);
const canvasGradient = ctx.createLinearGradient(0, 0, _x1, _y1);
gradient.colorStops.forEach(([offset, rgba]) => {
canvasGradient.addColorStop(offset, rgba);
});
ctx.fillStyle = canvasGradient;
ctx.fillRect(0, 0, canvaWidth, canvaHeight);
}
With this Im getting the following gradient:
The small one is the correct version (using background: linear-gradient(...)
) while the wrong one is the big one being draw in the canva.