How to Draw Custom Polygons with Pixi.js Graphics

Pixi.js offers robust support for rendering custom 2D shapes, and its Graphics object is fully capable of drawing complex, custom polygons. This article explains how to define custom paths using coordinate arrays, render concave and complex shapes, and utilize advanced techniques like adding holes to your custom polygons.

To draw a custom polygon in Pixi.js, you use the drawPolygon method of the PIXI.Graphics class. This method accepts a flat array of alternating X and Y coordinates, or an array of PIXI.Point objects.

Here is a basic example of how to draw a custom, five-pointed star polygon:

import * as PIXI from 'pixi.js';

const app = new PIXI.Application({ width: 800, height: 600 });
document.body.appendChild(app.view);

const graphics = new PIXI.Graphics();

// Define fill color and line style
graphics.beginFill(0x3498db);
graphics.lineStyle(4, 0xffffff, 1);

// Draw the custom polygon path [x1, y1, x2, y2, ...]
graphics.drawPolygon([
    400, 150,
    430, 240,
    520, 240,
    450, 300,
    480, 390,
    400, 330,
    320, 390,
    350, 300,
    280, 240,
    370, 240
]);

graphics.endFill();
app.stage.addChild(graphics);

Handling Complex and Concave Polygons

While Pixi.js easily renders simple convex and concave polygons, extremely complex self-intersecting polygons can sometimes render with unexpected artifacts due to how WebGL triangulates shapes. For standard complex shapes, Pixi.js manages triangulation automatically.

Drawing Polygons with Holes

If your complex polygon requires a transparent cutout or hole inside it, you can use the beginHole and endHole methods. This is essential for creating complex geometric shapes like donuts, frames, or custom stencils.

const complexShape = new PIXI.Graphics();

// Draw the outer polygon boundary
complexShape.beginFill(0xe74c3c);
complexShape.drawPolygon([
    100, 100,
    300, 100,
    300, 300,
    100, 300
]);

// Define the inner hole to subtract from the outer shape
complexShape.beginHole();
complexShape.drawPolygon([
    150, 150,
    250, 150,
    250, 250,
    150, 250
]);
complexShape.endHole();

complexShape.endFill();
app.stage.addChild(complexShape);

By leveraging drawPolygon, coordinate arrays, and hole definitions, you can construct virtually any custom 2D shape required for your Pixi.js application.