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
new PIXI.Graphics(): Instantiates a new graphics context which acts as a container for your vector shapes.beginFill(color, alpha): Specifies the color used to fill the shapes that are drawn subsequently. The color is defined as a hex code (e.g.,0xFF0000for red). You can optionally pass a second argument between0and1to set the opacity.drawRect(x, y, width, height): Draws a rectangle. The first two parameters define the X and Y coordinates of the top-left corner, while the last two define the width and height of the rectangle in pixels.endFill(): Applies the fill color defined inbeginFill()to the shapes drawn after it.addChild(): Renders the graphics object by adding it to the display list of the application stage.
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);