How to Add Stroke and Fill to Pixi.js Shapes

To apply both a line stroke and a solid fill color to a shape in Pixi.js, you use the Graphics class. This article provides a quick guide and code examples on how to combine these two properties to style your 2D vector shapes, covering both classic Pixi.js (v7 and below) and the modern Pixi.js (v8+) syntax.

Classic Method (PixiJS v7 and below)

In classic versions of Pixi.js, the order of operations is crucial. You must define the line style and the fill style before drawing the shape, and then close the path with endFill().

import * as PIXI from 'pixi.js';

// 1. Instantiate the Graphics object
const graphics = new PIXI.Graphics();

// 2. Define the outline (width, color in hex, alpha/opacity)
graphics.lineStyle(4, 0xFFFFFF, 1);

// 3. Define the solid fill (color in hex, alpha/opacity)
graphics.beginFill(0xFF0000, 1);

// 4. Draw the actual shape (x, y, width, height)
graphics.drawRect(50, 50, 150, 100);

// 5. Finalize the geometry
graphics.endFill();

Key Functions Explained:


Modern Method (PixiJS v8 and above)

If you are using PixiJS v8, the rendering engine utilizes a more modern, declarative chainable API. Instead of setting states beforehand, you define the geometry first, and then chain the .fill() and .stroke() methods.

import { Graphics } from 'pixi.js';

const graphics = new Graphics()
  .rect(50, 50, 150, 100)          // Define geometry
  .fill({ color: 0xFF0000 })       // Apply solid fill
  .stroke({ width: 4, color: 0xFFFFFF }); // Apply outline stroke

By chaining these methods, you can cleanly apply both fills and strokes to any standard or custom path in Pixi.js.