How to Create Soft Alpha Masks in Pixi.js
Creating a soft-edged alpha mask in Pixi.js allows you to smoothly blend and fade visual elements using a transparent PNG. This guide provides a direct, step-by-step walkthrough on how to load a gradient PNG, apply it as an alpha mask to a target sprite, and ensure the transparency renders correctly in your WebGL application.
Step 1: Prepare Your Assets
To create a soft mask, you need two images: 1. The Target Image: The texture or sprite you want to mask. 2. The Mask Image: A PNG with an alpha channel containing a soft gradient (e.g., a black-to-transparent radial gradient). Pixi.js uses the alpha channel of this image to determine the visibility of the target.
Step 2: Load the Textures and Create Sprites
Load both images into your Pixi.js application and convert them into sprites.
import * as PIXI from 'pixi.js';
// Create Pixi Application
const app = new PIXI.Application();
await app.init({ width: 800, height: 600 });
document.body.appendChild(app.canvas);
// Load textures
const targetTexture = await PIXI.Assets.load('path/to/target.jpg');
const maskTexture = await PIXI.Assets.load('path/to/soft-mask.png');
// Create Sprites
const targetSprite = new PIXI.Sprite(targetTexture);
const maskSprite = new PIXI.Sprite(maskTexture);Step 3: Apply the Mask
To apply the soft mask, assign the maskSprite to the
mask property of the targetSprite.
// Apply the mask
targetSprite.mask = maskSprite;Step 4: Add Both Sprites to the Stage
For the mask to render and transform correctly, both the target sprite and the mask sprite must be added to the stage.
// Add sprites to the scene container
app.stage.addChild(targetSprite);
app.stage.addChild(maskSprite);Step 5: Position and Scale
You can position, scale, or animate the mask sprite independently of the target sprite. The soft gradient will move dynamically over the target.
// Center the target sprite
targetSprite.x = app.screen.width / 2;
targetSprite.y = app.screen.height / 2;
targetSprite.anchor.set(0.5);
// Center the mask sprite over the target
maskSprite.x = targetSprite.x;
maskSprite.y = targetSprite.y;
maskSprite.anchor.set(0.5);Key Considerations
- Channel Masking: By default, Pixi.js uses the alpha channel of the mask sprite for WebGL masking. Ensure your PNG is saved with actual alpha transparency rather than a white-to-black color gradient.
- Performance: Sprite masking is highly optimized in WebGL. However, if you are animating or scaling large mask textures, ensure your asset dimensions are kept to the minimum size necessary for your desired visual quality.