Skip to content

Canvas 2D geometry

Path builders and angle maths for Canvas 2D. Every path function only builds the path — it never calls fill() or stroke(), so the caller decides how to paint it.

Usage

ts
import { roundRectByArc, getLinearGradient } from 'ranuts/utils';

const ctx = canvas.getContext('2d')!;

roundRectByArc(ctx, 10, 10, 200, 80, 12);
ctx.fillStyle = getLinearGradient(ctx, 10, 10, 200, 80, 'linear-gradient(90deg, #06f, #0cf)');
ctx.fill();

API

getAngle

Degrees to radians.

Parameters

ParameterDescriptionTypeDefault
degAngle in degreesnumberRequired

Return

ArgumentDescriptionType
radAngle in radiansnumber

getArcPointerByDeg

The point on a circle at a given angle.

Parameters

ParameterDescriptionTypeDefault
degAngle in radiansnumberRequired
rRadiusnumberRequired

Return

ArgumentDescriptionType
point[x, y][number, number]

getTangentByPointer

The tangent line at a point on a circle.

Parameters

ParameterDescriptionTypeDefault
xx coordinatenumberRequired
yy coordinatenumberRequired

Return

ArgumentDescriptionType
line[slope, intercept]Array<number>

roundRectByArc

Trace a rounded rectangle. A corner radius larger than half the shorter side is clamped to half, so adjacent corners can never overlap.

Parameters

ParameterDescriptionTypeDefault
ctxCanvas 2D contextCanvasRenderingContext2DRequired
...restx, y, w, h, rnumber[]Required

Return

No return value (void)

fanShapedByArc

Trace a pie slice, including the gutter between slices.

Parameters

ParameterDescriptionTypeDefault
ctxCanvas 2D contextCanvasRenderingContext2DRequired
maxRadiusOuter radiusnumberRequired
startStart angle in radiansnumberRequired
endEnd angle in radiansnumberRequired
gutterWidth of the gap between slicesnumberRequired

Return

No return value (void)

getLinearGradient

Translate a CSS linear-gradient(...) string into a Canvas CanvasGradient.

createLinearGradient only takes a start and an end point, while CSS describes direction as an angle — so the circle is split into eight 45° sectors and the tangent turns the angle back into start/end coordinates on the rectangle's boundary. Keyword directions (to top / to bottom / to left / to right) are handled directly.

Parameters

ParameterDescriptionTypeDefault
ctxCanvas 2D contextCanvasRenderingContext2DRequired
xx of the rectangle's top-left cornernumberRequired
yy of the rectangle's top-left cornernumberRequired
wRectangle widthnumberRequired
hRectangle heightnumberRequired
backgrounde.g. linear-gradient(90deg, red, blue)stringRequired

Return

ArgumentDescriptionType
gradientAssignable straight to fillStyle / strokeStyleCanvasGradient

WARNING

Colour stops must be unitless (red 0, blue 1). A percentage stop (red 50%) parses to NaN and addColorStop will throw.

Released under the MIT License.