packages/core/src/lib/geometry/rectangle.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import {
2 resolveNumericCornerRadii,
3 type RoundedCornerPathOptions,
4 } from './rounded-corners.js';
5 import { finiteNumber } from './validation.js';
6
7 /**
8 * Geometry and construction options for a rectangle path.
9 *
10 * @see {@link RoundedCornerPathOptions}
11 * @see {@link createRectanglePath}
12 */
13 export interface RectanglePathOptions extends RoundedCornerPathOptions {
14 /**
15 * Horizontal coordinate or displacement in the containing coordinate system. See
16 * {@link RectanglePathOptions}.
17 */
18 x?: number;
19 /**
20 * Vertical coordinate or displacement in the containing coordinate system. See
21 * {@link RectanglePathOptions}.
22 */
23 y?: number;
24 /**
25 * Horizontal extent in the units of the containing geometry or surface. See
26 * {@link RectanglePathOptions}.
27 */
28 width: number;
29 /**
30 * Vertical extent in the units of the containing geometry or surface. See
31 * {@link RectanglePathOptions}.
32 */
33 height: number;
34 }
35
36 /**
37 * Creates a Canvas Path2D for rectangle geometry from validated options.
38 *
39 * @param options - Rectangle bounds and corner options. See {@link RectanglePathOptions}.
40 * @returns A native Canvas path containing the rectangle.
41 *
42 * @see {@link RectanglePathOptions}
43 */
44 export function createRectanglePath(
45 options: Readonly<RectanglePathOptions>,
46 ): Path2D {
47 const x = finiteNumber(options.x ?? 0, 'x');
48 const y = finiteNumber(options.y ?? 0, 'y');
49 const width = finiteNumber(options.width, 'width');
50 const height = finiteNumber(options.height, 'height');
51 const radii = resolveNumericCornerRadii(4, options);
52 const path = new Path2D();
53
54 if (radii.every(radius => radius === 0)) {
55 path.rect(x, y, width, height);
56 } else {
57 path.roundRect(x, y, width, height, [...radii]);
58 }
59
60 return path;
61 }
62
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision 2dccb19. ALPHA — NOT FOR PRODUCTION USE.