src/assets/__docs__/svg.mdx
PixiJS supports SVG rendering, letting you integrate scalable vector graphics into your projects. This guide covers different ways to use SVGs, including real-time rendering, performance trade-offs, and known limitations.
SVGs have several advantages over raster images like PNGs:
However, SVGs can also be computationally expensive to parse, particularly for intricate illustrations with many paths or effects.
PixiJS offers two primary ways to render SVGs:
Each method has its own trade-offs, covered below.
SVGs can be loaded as textures and used within Sprites. This method is efficient but does not retain the scalability of vector graphics.
const svgTexture = await Assets.load('tiger.svg');
const mySprite = new Sprite(svgTexture);
@stackblitz(sprite_svg)
You can specify a resolution when loading an SVG as a texture to control its size. This increases memory usage but produces higher fidelity.
const svgTexture = await Assets.load({
src: 'path/to.svg',
data: {
resolution: 4,
}
});
const mySprite = new Sprite(svgTexture);
@stackblitz(sprite_svg_custom-data)
Pros:
Cons:
PixiJS can render SVGs as scalable vector graphics using the Graphics class.
const graphics = new Graphics().svg('<svg width="100" height="100"><rect width="100" height="100" fill="red"/></svg>');
@stackblitz(graphics_svg_string-parsing)
If you want to use the same SVG multiple times, use GraphicsContext to share the parsed SVG data across multiple graphics objects. This parses it once and reuses the result.
const context = new GraphicsContext().svg(
'<svg width="100" height="100"><rect width="100" height="100" fill="red"/></svg>',
);
const graphics1 = new Graphics(context);
const graphics2 = new Graphics(context);
Instead of passing an SVG string directly, load an SVG file using Assets.load. This returns a GraphicsContext object for creating multiple Graphics instances efficiently.
const svgContext = await Assets.load('path/to.svg', {
parseAsGraphicsContext: true, // If false, returns a texture instead
});
const myGraphics = new Graphics(svgContext);
Since it's loaded via Assets.load, the result is cached and reused, similar to a texture.
@stackblitz(graphics_svg_file)
Pros:
Cons:
PixiJS supports most SVG features that can be rendered in a Canvas 2D context:
| Feature | Supported |
|---|---|
| Basic Shapes (rect, circle, path, etc.) | Yes |
| Gradients | Yes |
| Stroke and fill styles | Yes |
| Text elements | No |
| Filters (Blur, Drop Shadow, etc.) | No |
| Clipping paths | Yes |
| Patterns | No |
| Complex paths and curves | Yes |
GraphicsContext to cache and reuse parsed data.