How to Compute Precise Angled Linear Gradient Coordinates for Canvas Text
This guide explains how to calculate the exact start and end points of an angled linear gradient that fills text on an HTML canvas, covering the necessary geometry, trigonometric formulas, step‑by‑step derivations, and practical code snippets for accurate rendering.
Gradient Start and End Coordinates
To compute the start and end points of a linear gradient that exactly covers a rectangular text area of width W, height H, with top‑left corner ( X, Y) and angle A (0° at the 3 o’clock direction, measured counter‑clockwise), follow these steps:
Calculate the gradient line length using the rectangle dimensions and the angle.
Derive the half‑length and use the rectangle centre to obtain the coordinates.
Gradient line length
The W3C specification defines the length for a gradient measured clockwise from 12 o’clock. Adjusting to the 3 o’clock reference gives:
gradientLineLength = abs(W * cos(A)) + abs(H * sin(A))
halfGradientLineLength = gradientLineLength / 2Absolute values are required because sin and cos can be negative over their periods.
Rectangle centre
centerX = X + W / 2
centerY = Y + H / 2Start and end points
startX = centerX - cos(A) * halfGradientLineLength
startY = centerY + sin(A) * halfGradientLineLength
endX = centerX + cos(A) * halfGradientLineLength
endY = centerY - sin(A) * halfGradientLineLengthPractical tip
Avoid using tan as an intermediate value because it becomes undefined (infinite) when the cosine of the angle is zero. Using sin and cos directly yields stable, concise code.
References
Do you really know CSS linear‑gradients? – https://medium.com/@patrickbrosset/do-you-really-understand-css-linear-gradients-631d9a895caf
MDN Web Docs – linear‑gradient – https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
W3C CSS Images Module Level 3 – linear‑gradients – https://drafts.csswg.org/css-images-3/#linear-gradients
Aotu Lab
Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
