How to Draw a Rectangle in Pixi.js Graphics

Drawing basic shapes is a fundamental task when working with Pixi.js, a popular 2D rendering engine for the web. This article provides a quick, step-by-step guide on how to instantiate the Graphics class, define a specific fill color, and render a basic rectangle onto your canvas.

Step-by-Step Implementation

To draw a colored rectangle in Pixi.js, you use the PIXI.Graphics class. This class contains methods to draw paths, lines, and shapes.

Below is the complete, modern JavaScript code required to draw a solid red rectangle and add it to the stage:

import * as PIXI from 'pixi.js';

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

// 2. Create a new Graphics object
const graphics = new PIXI.Graphics();

// 3. Set the fill color (Hexadecimal format)
graphics.beginFill(0xFF0000); // Red

// 4. Define the rectangle: drawRect(x, y, width, height)
graphics.drawRect(50, 50, 200, 100);

// 5. Complete the fill action
graphics.endFill();

// 6. Add the graphics to the active stage
app.stage.addChild(graphics);

Understanding the Methods

Note for PixiJS v8 Users

If you are using PixiJS version 8 or newer, the Graphics API has been streamlined to support chainable methods. The syntax for drawing a colored rectangle in v8 is as follows:

const graphics = new PIXI.Graphics()
    .rect(50, 50, 200, 100)
    .fill({ color: 0xFF0000 });

app.stage.addChild(graphics);