Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Getting Started with PixiJS: A Practical Guide to 2D Rendering

Tech May 7 3

Web development increasingly relies on graphics and animations to create engaging user experiences. PixiJS stands out as a powerful 2D rendering engine that enables developers to create stunning visual content with excellent performance. This guide covers the essential concepts needed to start building interactive 2D graphics with PixiJS.

Environment Setup

PixiJS can be integrated into projects using either CDN or NPM. Both approaches are straightforward and depend on your project requirements.

CDN Installation

For quick prototyping and learning purposes, the CDN approach works well:

<script src="https://pixijs.download/release/pixi.js"></script>

NPM Installation

For production applications, install via npm:

npm install pixi.js

Then import in your JavaScript files:

import * as PIXI from 'pixi.js';

Additional Packages

Some advanced shapes require the graphics-extras package:

npm install @pixi/graphics-extras

Or via CDN:

<script src="https://cdn.jsdelivr.net/npm/@pixi/graphics-extras@7.x/dist/graphics-extras.min.js"></script>

Creating the Application

The first step involves initializing the PixiJS application and adding it to the DOM.

Basic Setup

// Initialize the PixiJS application
const app = new PIXI.Application();

// Add the canvas to the document
document.body.appendChild(app.view);

Specifying Dimensions

The default canvas size is 800x600 pixels. Override this during initialization:

const app = new PIXI.Application({
  width: 640,
  height: 360
});

document.body.appendChild(app.view);

Custom Background Color

Canvas background defaults to black. Customize using the backgroundColor option:

const app = new PIXI.Application({
  width: 640,
  height: 360,
  backgroundColor: 0x1099bb  // Hex color value
});

document.body.appendChild(app.view);

The backgroundColor accepts various formats:

  • Color keywords: backgroundColor: 'pink'
  • RGB strings: backgroundColor: 'rgb(100, 0, 100)'
  • Hex strings: backgroundColor: '#1182af'
  • Hex numbers: backgroundColor: 0x1182af

Responsive Canvas

To make the canvas fill its parent element:

const app = new PIXI.Application({
  resizeTo: window
});

Add CSS to prevent scrollbars:

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

canvas {
  display: block;
}

Destroying the Canvas

Clean up resources when no longer needed:

// Removes the canvas from memory
app.destroy();

// Removes the canvas element from the DOM as well
app.destroy(true);

Drawing Basic Shapes

PixiJS provides the Graphics class for creating vector shapes. The general workflow involves:

  1. Instantiate the Graphics class
  2. Set fill or stroke properties
  3. Draw the shape
  4. Call the appropriate draw method

Rectangle

const graphics = new PIXI.Graphics();

// Set fill color and opacity
graphics.beginFill(0xFFD700, 1);

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

graphics.endFill();

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

Rounded Rectangle

graphics.beginFill(0xFFD700, 1);
graphics.drawRoundedRect(50, 50, 200, 100, 15);
graphics.endFill();
app.stage.addChild(graphics);

Circle

graphics.beginFill(0xFF6B6B, 1);
graphics.drawCircle(150, 150, 50);
graphics.endFill();
app.stage.addChild(graphics);

Ellipse

graphics.beginFill(0x4ECDC4, 1);
graphics.drawEllipse(150, 100, 80, 40);
graphics.endFill();
app.stage.addChild(graphics);

Polygon

Define polygons using an array of coordinate pairs:

const path = [
  150, 50,   // First vertex
  200, 150,  // Second vertex
  100, 150   // Third vertex
];

graphics.beginFill(0x95E1D3, 1);
graphics.drawPolygon(path);
graphics.endFill();
app.stage.addChild(graphics);

Star

The drawStar method requires the graphics-extras package:

graphics.beginFill(0xF38181, 1);
graphics.drawStar(150, 150, 5, 60, 30);
graphics.endFill();
app.stage.addChild(graphics);

Regular Polygon

graphics.beginFill(0xAA96DA, 1);
graphics.drawRegularPolygon(150, 150, 50, 6);
graphics.endFill();
app.stage.addChild(graphics);

Rounded Regular Polygon

graphics.beginFill(0xFCBAD3, 1);
graphics.drawRoundedPolygon(150, 150, 60, 6, 10);
graphics.endFill();
app.stage.addChild(graphics);

Torus (Ring)

graphics.beginFill(0xA8D8EA, 1);
graphics.drawTorus(150, 150, 30, 60);
graphics.endFill();
app.stage.addChild(graphics);

Lines and Curves

Polyline

Use moveTo and lineTo for drawing polylines:

const lineGraphics = new PIXI.Graphics();
lineGraphics.lineStyle(4, 0xFFD700, 1);

lineGraphics.moveTo(20, 50);
lineGraphics.lineTo(80, 20);
lineGraphics.lineTo(120, 80);
lineGraphics.lineTo(180, 40);

app.stage.addChild(lineGraphics);

Closed Path

Add closePath to create a closed shape:

lineGraphics.moveTo(20, 20);
lineGraphics.lineTo(100, 20);
lineGraphics.lineTo(100, 100);
lineGraphics.lineTo(20, 100);
lineGraphics.closePath();

Arc

Draw arcs using the arc method:

graphics.lineStyle(3, 0xFF6B6B, 1);
graphics.arc(150, 150, 60, 0, Math.PI * 1.5);
app.stage.addChild(graphics);

Quadratic Bezier Curve

graphics.lineStyle(3, 0x4ECDC4, 1);
graphics.moveTo(50, 150);
graphics.quadraticCurveTo(100, 50, 150, 150);
app.stage.addChild(graphics);

Cubic Bezier Curve

graphics.lineStyle(3, 0x95E1D3, 1);
graphics.moveTo(50, 150);
graphics.bezierCurveTo(100, 50, 200, 250, 250, 150);
app.stage.addChild(graphics);

Text Rendering

PixiJS handles text rendering through the Text class:

const text = new PIXI.Text('Hello World');
app.stage.addChild(text);

Text Styling

Pass a style object as the second parameter:

const styledText = new PIXI.Text('Hello World', {
  fontFamily: 'Arial',
  fontSize: 36,
  fill: 0xFFFFFF,
  stroke: 0xFF0000,
  strokeThickness: 4,
  dropShadow: true,
  dropShadowColor: '#000000',
  dropShadowBlur: 4,
  dropShadowAngle: Math.PI / 4,
  dropShadowDistance: 6
});

app.stage.addChild(styledText);

Gradient Text

Use an array of colors for gradient fills:

const gradientText = new PIXI.Text('Gradient Text', {
  fontSize: 48,
  fontWeight: 'bold',
  fill: ['#FF6B6B', '#4ECDC4', '#45B7D1'],
  fillGradientType: PIXI.TEXT_GRADIENT.LINEAR_HORIZONTAL
});

app.stage.addChild(gradientText);

Working with Images

Display images using Sprites and Textures:

// Load texture from file
const texture = PIXI.Texture.from('./image.png');
const sprite = new PIXI.Sprite(texture);

app.stage.addChild(sprite);

Loading Remote Images

const remoteTexture = PIXI.Texture.from('https://example.com/image.png');
const remoteSprite = new PIXI.Sprite(remoteTexture);
app.stage.addChild(remoteSprite);

Sprite Properties

sprite.x = 100;
sprite.y = 100;
sprite.width = 200;
sprite.height = 150;
sprite.rotation = Math.PI / 4;  // 45 degrees
sprite.alpha = 0.8;
sprite.visible = true;

Graphics Styling

Fill Styles

The beginFill method accepts color and alpha values:

graphics.beginFill(0xFF6B6B);        // Red with full opacity
graphics.beginFill(0xFF6B6B, 0.5);   // Red with 50% opacity
graphics.beginFill('hotpink');       // Color keyword
graphics.beginFill('#FF6B6B');       // Hex string

Stroke Styles

Use lineStyle for outlines:

graphics.lineStyle(2, 0xFFFFFF, 1);  // width, color, alpha
graphics.drawRect(50, 50, 100, 100);

Filters

PixiJS includes built-in filters for visual effects.

Blur Filter

const blurFilter = new PIXI.BlurFilter(5);
sprite.filters = [blurFilter];

Alpha Filter

const alphaFilter = new PIXI.AlphaFilter(0.5);
sprite.filters = [alphaFilter];

Values outside 0-1 create interesting effects:

  • Above 1: Overexposure
  • Below 0: Complete transparency

Combining Filters

Apply multiple filters to a single element:

sprite.filters = [blurFilter, alphaFilter];

Interactive Events

Enable interactivity on graphics elements:

const interactiveRect = new PIXI.Graphics();
interactiveRect.beginFill(0xFF6B6B);
interactiveRect.drawRect(0, 0, 100, 100);
interactiveRect.endFill();

// Enable interactivity
interactiveRect.interactive = true;
interactiveRect.cursor = 'pointer';

// Add click listener
interactiveRect.on('click', () => {
  console.log('Rectangle clicked');
});

app.stage.addChild(interactiveRect);

Touch Events

For mobile devices, use tap instead of click:

interactiveRect.on('tap', () => {
  console.log('Rectangle tapped');
});

Other Event Types

  • pointerdown: Pressed
  • pointerup: Released
  • pointerover: Hovered
  • pointerout: Left hover
  • pointermove: Moving over element

Animation with Ticker

The ticker manages the animation loop, executing code on every frame.

Basic Rotation

const rotatingRect = new PIXI.Graphics();
rotatingRect.beginFill(0xFF6B6B);
rotatingRect.drawRect(-32, -32, 64, 64);  // Centered at origin
rotatingRect.endFill();

rotatingRect.x = app.screen.width / 2;
rotatingRect.y = app.screen.height / 2;

app.stage.addChild(rotatingRect);

app.ticker.add((delta) => {
  rotatingRect.rotation += 0.05 * delta;
});

The delta parameter accounts for frame rate differences, ensuring consistent animation speed across devices.

Center Pivot

By default, shapes rotate around their top-left corner. Set the pivot to rotate around the center:

rectangle.pivot.set(32, 32);  // Half of width and height

Additional Resources

This guide covers the fundamental concepts of PixiJS. The library offers many more features including:

  • Advanced particle systems
  • Container hierarchies for complex scenes
  • Render textures for off-screen rendering
  • Masking and blending modes
  • Integration with physics engines
Tags: PixiJS

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.