Skip to main content

usePolygon

Hook used to create basic polygons, both regular and irregular polygons with different configurations.

It is aliased to create other regular polygons such as useTriangle, useSquare, etc.

usePolygon({ sides: 3 });usePolygon({ sides: 4 });usePolygon({ sides: 5 });

Configuration

(PolygonConfig | undefined) usePolygon accepts two different ways to configure a polygon:

1. Regular polygon

PropertyTypeDefaultDescription
sidesnumber4The number of sides.
sideLengthnumber100The length of each side (optional).
sizenumber100The diameter of circumscribed circle that polygon drawn in (optional).
tip

When defining any regular polygon, you can specify either sideLength or size.

If you define both, size will always take precedence.

2. Irregular polygon

useLine({ vertices: [ { x: 40, y: 0 }, { x: 290, y: 20 }, { x: 350, y: 200 }, { x: 80, y: 180 }, { x: 0, y: 250 }, ],});
PropertyTypeDefaultDescription
verticesVertex[][]Vertices of the polygon (at least 3 needed).

extends Primitive Configuration

(PrimitiveConfig) Base configurations for all primitives.

PropertyTypeDefaultDescription
scalenumber | Vertex1Scaling factor of the primitive. If Vertex is provided, it will scale x and y dimension accordingly (optional).
rotatenumber0Rotation of the primitive, in degrees, in clockwise manner (optional).
positionVertex{ x: 0, y: 0 }Moving distance away from the primitive drawing centre. By default, primitive will start drawing in origin (0, 0) (optional).
info

scale, rotate and position can be considered as transformation of polygon after drawn, where position can be considered as transform: translate of css to the primitive.

The polygon will first be scaled, then rotated and lastly, translated.

Returns

(Primitive) All primitive return the following properties:

PropertyTypeDescription
verticesVertex[]Vertices of the primitive.
edgesEdge[]Edges of the primitive.
facesFace[]Faces of the primitive.
centroidVertexCentroid (geometric centre) of primitive.
boundingBoxBoundingBoxSpace constraint of the primitive, with properties x, y, width and height.
svgPathstringSVG path representing the shape of the primitive.
drawToCanvas(ctx: CanvasRenderingContext2D) => voidCallback that draws the primitive to a canvas context.
modifyConfig(newConfig: Partial<PolygonConfig>) => voidCallback to update the configuration of the primitive.

Example

import { usePolygon } from "react-use-plygon";

// A pentagon with 20px of length and 5px right and 8px down from the origin
const polygon1 = usePolygon({
sides: 5,
sideLength: 20,
position: { x: 5, y: 8 },
});

// An isosceles triangle with custom vertices
const polygon2 = usePolygon({
vertices: [
{ x: 0, y: 0 },
{ x: 4, y: 0 },
{ x: 2, y: 2 },
],
});