Skip to main content

SVG

概述

¥Overview

PixiJS 为渲染 SVG 提供强大的支持,允许开发者将可缩放矢量图形无缝集成到他们的项目中。本指南探讨了在 PixiJS 中使用 SVG 的不同方法,涵盖实时渲染、性能优化和潜在陷阱。

¥PixiJS provides powerful support for rendering SVGs, allowing developers to integrate scalable vector graphics seamlessly into their projects. This guide explores different ways to use SVGs in PixiJS, covering real-time rendering, performance optimizations, and potential pitfalls.


为什么使用 SVG?

¥Why Use SVGs?

与 PNG 等光栅图片相比,SVG 有几个优势:

¥SVGs have several advantages over raster images like PNGs:

✅ 文件大小更小 - SVG 可以比 PNG 小得多,尤其是对于大而简单的形状。高分辨率 PNG 可能有几兆字节,而等效 SVG 可能只有几千字节。

¥✅ Smaller File Sizes – SVGs can be significantly smaller than PNGs, especially for large but simple shapes. A high-resolution PNG may be several megabytes, while an equivalent SVG could be just a few kilobytes.

✅ 可扩展性 - SVG 可以缩放而不会损失质量,非常适合响应式应用和 UI 元素。

¥✅ Scalability – SVGs scale without losing quality, making them perfect for responsive applications and UI elements.

✅ 渲染后可编辑 - 与纹理不同,通过 Graphics 渲染的 SVG 可以动态修改(例如,更改描边颜色、修改形状)。

¥✅ Editable After Rendering – Unlike textures, SVGs rendered via Graphics can be modified dynamically (e.g., changing stroke colors, modifying shapes).

✅ 适用于简单图形 - 如果图形由基本形状和路径组成,则可以将 SVG 高效地渲染为矢量图形。

¥✅ Efficient for Simple Graphics – If the graphic consists of basic shapes and paths, SVGs can be rendered efficiently as vector graphics.

但是,解析 SVG 的计算成本也很高,尤其是对于具有许多路径或效果的复杂插图。

¥However, SVGs can also be computationally expensive to parse, particularly for intricate illustrations with many paths or effects.


在 PixiJS 中渲染 SVG 的方法

¥Ways to Render SVGs in PixiJS

PixiJS 提供两种主要的 SVG 渲染方式:

¥PixiJS offers two primary ways to render SVGs:

  1. 作为纹理 - 将 SVG 转换为纹理以渲染为精灵。

    ¥As a Texture – Converts the SVG into a texture for rendering as a sprite.

  2. 作为图形对象 - 解析 SVG 并将其渲染为矢量几何图形。

    ¥As a Graphics Object – Parses the SVG and renders it as vector geometry.

每种方法都有其优点和用例,我们将在下面进行探讨。

¥Each method has its advantages and use cases, which we will explore below.


1. 将 SVG 渲染为纹理

¥ Rendering SVGs as Textures

概述

¥Overview

SVG 可以作为纹理加载并在 Sprite 中使用。此方法高效,但不保留矢量图形的可扩展性。

¥SVGs can be loaded as textures and used within Sprites. This method is efficient but does not retain the scalability of vector graphics.

示例

¥Example

const svgTexture = await Assets.load('tiger.svg');
const mySprite = new Sprite(svgTexture);

缩放纹理

¥Scaling Textures

在将 SVG 作为纹理加载时,你可以指定分辨率来控制其大小:这确实会增加内存使用量,但保真度更高。

¥You can specify a resolution when loading an SVG as a texture to control its size: This does increase memory usage, but it be of a higher fidelity.

const svgTexture = await Assets.load('path/to.svg', {
resolution: 4 // will be 4 times as big!
});
const mySprite = new Sprite(svgTexture);

这可确保纹理以正确的大小和分辨率显示。

¥This ensures the texture appears at the correct size and resolution.

优点和缺点

¥Pros & Cons

✅ 渲染速度快(渲染为四边形,而不是几何体)✅ 适合静态图片✅ 支持分辨率缩放以实现精确大小✅ 非常适合不需要清晰矢量缩放的复杂 SVG(例如,具有固定尺寸的 UI 组件)❌ 缩放不干净(缩放可能会导致像素化)❌ 灵活性较差(无法动态修改形状)❌ 纹理大小限制纹理最多只能为 4096x4096 像素,因此如果你需要渲染更大的 SVG,则需要使用 Graphics 方法。

¥✅ Fast to render (rendered as a quad, not geometry)\ ✅ Good for static images\ ✅ Supports resolution scaling for precise sizing\ ✅ Ideal for complex SVGs that do not need crisp vector scaling (e.g., UI components with fixed dimensions)\ ❌ Does not scale cleanly (scaling may result in pixelation)\ ❌ Less flexibility (cannot modify the shape dynamically) ❌ Texture Size Limit A texture can only be up to 4096x4096 pixels, so if you need to render a larger SVG, you will need to use the Graphics method.

最佳用例

¥Best Use Cases

  • 背景图片

    ¥Background images

  • 装饰元素

    ¥Decorative elements

  • 不需要缩放的性能关键型应用

    ¥Performance-critical applications where scaling isn’t needed

  • 不需要清晰矢量缩放的复杂 SVG(例如,固定大小的 UI 组件)

    ¥Complex SVGs that do not require crisp vector scaling (e.g., fixed-size UI components)


2. 将 SVG 渲染为图形

¥ Rendering SVGs as Graphics

概述

¥Overview

PixiJS 可以使用 Graphics 类将 SVG 渲染为真正的可缩放矢量图形。

¥PixiJS can render SVGs as real scalable vector graphics using the Graphics class.

示例

¥Example

const graphics = new Graphics()
.svg('<svg width="100" height="100"><rect width="100" height="100" fill="red"/></svg>');

如果你想多次使用同一个 SVG,则可以使用 GraphicsContext 在多个图形对象之间共享已解析的 SVG 数据,通过解析一次并重复使用来提高性能。

¥If you want to use the same SVG multiple times, you can use GraphicsContext to share the parsed SVG data across multiple graphics objects, improving performance by parsing it once and reusing it.

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);

将 SVG 加载为图形

¥Loading SVGs as Graphics

你可以使用 PixiJS 的 Assets.load 方法加载 SVG 文件,而不是直接传递 SVG 字符串。这将返回一个 GraphicsContext 对象,可用于高效地创建多个 Graphics 对象。

¥Instead of passing an SVG string directly, you can load an SVG file using PixiJS’s Assets.load method. This will return a GraphicsContext object, which can be used to create multiple Graphics objects efficiently.

const svgContext = await Assets.load('path/to.svg', {
parseAsGraphicsContext: true // If false, it returns a texture instead.
});
const myGraphics = new Graphics(svgContext);

由于它是通过 Assets.load 加载的,因此它将被缓存和重用,就像纹理一样。

¥Since it's loaded via Assets.load, it will be cached and reused, much like a texture.


优点和缺点

¥Pros & Cons

✅ 保留矢量可扩展性(缩放时无像素化)✅ 渲染后可修改(更改颜色、笔触等)✅ 适用于简单图形✅ 如果 SVG 结构不变,则渲染速度快(无需重新解析)❌ 解析成本更高(复杂的 SVG 渲染速度可能很慢)❌ 不适合静态图片

¥✅ Retains vector scalability (no pixelation when zooming)\ ✅ Modifiable after rendering (change colors, strokes, etc.)\ ✅ Efficient for simple graphicsfast rendering if SVG structure does not change (no need to reparse) ❌ More expensive to parse (complex SVGs can be slow to render)\ ❌ Not ideal for static images

最佳用例

¥Best Use Cases

  • 需要调整大小的图标和 UI 元素

    ¥Icons and UI elements that need resizing

  • 当玩家放大时需要保持清晰的游戏世界

    ¥A game world that needs to remain crisp as a player zooms in

  • 需要动态修改 SVG 的交互式图形

    ¥Interactive graphics where modifying the SVG dynamically is necessary


SVG 渲染注意事项

¥SVG Rendering Considerations

支持的功能

¥Supported Features

PixiJS 支持大多数可以在 Canvas 2D 上下文中渲染的 SVG 功能。以下是常见 SVG 功能及其兼容性的列表:

¥PixiJS supports most SVG features that can be rendered in a Canvas 2D context. Below is a list of common SVG features and their compatibility:

特性支持
基本形状(矩形、圆形、路径等)
渐变
描边和填充样式
文本元素
滤镜(模糊、阴影等)
剪切路径
图案
复杂路径和曲线

性能注意事项

¥Performance Considerations

  • 复杂 SVG:大型或复杂的 SVG 可能会因解析成本高而减慢渲染启动速度。使用 GraphicsContext 缓存和重用已解析的数据。

    ¥Complex SVGs: Large or intricate SVGs can slow down rendering start up due to high parsing costs. Use GraphicsContext to cache and reuse parsed data.

  • 矢量与纹理:如果性能是一个问题,请考虑使用 SVG 作为纹理,而不是将它们渲染为几何图形。但是,请记住,纹理会占用更多内存。

    ¥Vector vs. Texture: If performance is a concern, consider using SVGs as textures instead of rendering them as geometry. However, keep in mind that textures take up more memory.

  • 实时渲染:避免动态渲染复杂的 SVG。尽可能预加载并重用它们。

    ¥Real-Time Rendering: Avoid rendering complex SVGs dynamically. Preload and reuse them wherever possible.


最佳实践和陷阱

¥Best Practices & Gotchas

最佳实践

¥Best Practices

✅ 将 Graphics 用于可扩展和动态 SVG ✅ 将 Textures 用于性能敏感型应用✅ 使用 GraphicsContext 避免冗余解析✅ 使用纹理时考虑使用 resolution 来平衡质量和内存

¥✅ Use Graphics for scalable and dynamic SVGs\ ✅ Use Textures for performance-sensitive applications\ ✅ Use GraphicsContext to avoid redundant parsing\ ✅ Consider resolution when using textures to balance quality and memory

陷阱

¥Gotchas

⚠ 大型 SVG 解析速度可能很慢 - 在 PixiJS 中使用 SVG 之前,请对其进行优化。⚠ 基于纹理的 SVG 无法干净地缩放 - 必要时请使用更高的分辨率。⚠ 并非所有 SVG 功能都受支持 - 复杂的过滤器和文本元素可能无法按预期工作。

¥⚠ Large SVGs can be slow to parse – Optimize SVGs before using them in PixiJS.\ ⚠ Texture-based SVGs do not scale cleanly – Use higher resolution if necessary.\ ⚠ Not all SVG features are supported – Complex filters and text elements may not work as expected.


通过了解 PixiJS 如何处理 SVG,开发者可以做出明智的决定,确定何时使用 Graphics.svg()GraphicsContext 或 SVG 纹理,平衡特定用例的质量和性能。

¥By understanding how PixiJS processes SVGs, developers can make informed decisions on when to use Graphics.svg(), GraphicsContext, or SVG textures, balancing quality and performance for their specific use case.