Apply Drop Shadow and Text Stroke in Pixi.js
This article explains how to enhance typography in Pixi.js by
applying visual effects such as drop shadows and text strokes. You will
learn how to configure the TextStyle class properties to
customize outline thickness, shadow distance, color, angle, and blur,
allowing you to create visually appealing text for your HTML5
applications and games.
Using the TextStyle Class
In Pixi.js, text styling is managed through the
TextStyle class. To apply strokes and drop shadows, you
define these properties within a style configuration object and pass it
when instantiating a new Text object.
Adding a Text Stroke
A text stroke (or outline) is created using two primary properties:
stroke and strokeThickness.
stroke: Defines the color of the outline (hexadecimal or color string).strokeThickness: Determines the width of the outline in pixels.strokeLinejoin: (Optional) Controls the corners of the stroke, such as ‘round’, ‘miter’, or ‘bevel’.
Adding a Drop Shadow
A drop shadow adds depth to your text. To enable and customize it, use the following properties:
dropShadow: Must be set totrueto enable the effect.dropShadowColor: The color of the shadow.dropShadowAlpha: The opacity of the shadow (0 to 1).dropShadowAngle: The direction of the shadow in radians (e.g.,Math.PI / 6).dropShadowDistance: The distance of the shadow from the text in pixels.dropShadowBlur: The softness or blur radius of the shadow.
Complete Code Example
Below is a complete, direct implementation demonstrating how to apply both effects to a single text object in Pixi.js.
import { Application, Text, TextStyle } from 'pixi.js';
// Initialize PixiJS Application
const app = new Application();
await app.init({ width: 800, height: 600, backgroundColor: 0x1099bb });
document.body.appendChild(app.canvas);
// Create the visual style
const style = new TextStyle({
fontFamily: 'Arial',
fontSize: 48,
fontWeight: 'bold',
fill: '#ffffff', // Main text color
// Stroke (Outline) Settings
stroke: '#000000',
strokeThickness: 6,
strokeLinejoin: 'round',
// Drop Shadow Settings
dropShadow: true,
dropShadowColor: '#000000',
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6, // Direction of the shadow
dropShadowDistance: 6,
dropShadowAlpha: 0.8
});
// Create the Text object with the style
const richText = new Text({
text: 'Pixi.js Text Effects',
style: style
});
// Position text in the center of the screen
richText.x = app.screen.width / 2;
richText.y = app.screen.height / 2;
richText.anchor.set(0.5);
// Add text to the canvas
app.stage.addChild(richText);By adjusting the strokeThickness and
dropShadowBlur values, you can achieve various stylistic
results, from sharp retro game fonts to soft, modern UI typography.