pixijs-scene-gif

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
GifSprite
plays an animated GIF as a display object.
Assets.load('animation.gif')
returns a
GifSource
(not a
Texture
), and you wrap that in a
GifSprite
. Requires a side-effect
import 'pixi.js/gif'
to register the loader extension.
Assumes familiarity with
pixijs-scene-core-concepts
.
GifSprite
extends
Sprite
, so it is a leaf: do not nest children inside it. Wrap multiple
GifSprite
instances in a
Container
to group them.
GifSprite
作为显示对象播放动画GIF。
Assets.load('animation.gif')
返回
GifSource
(而非
Texture
),你需要将其包装在
GifSprite
中使用。需要导入副作用模块
import 'pixi.js/gif'
来注册加载器扩展。
假设你已熟悉
pixijs-scene-core-concepts
GifSprite
继承自
Sprite
,因此它是叶子节点:不要在其中嵌套子元素。如需分组多个
GifSprite
实例,请将它们包装在
Container
中。

Quick Start

快速开始

ts
import "pixi.js/gif";
import { GifSprite } from "pixi.js/gif";

const source = await Assets.load("animation.gif");

const gif = new GifSprite({
  source,
  autoPlay: true,
  loop: true,
  animationSpeed: 1,
});

gif.anchor.set(0.5);
gif.x = app.screen.width / 2;
gif.y = app.screen.height / 2;

app.stage.addChild(gif);
[!NOTE] GIFs decode every frame into a separate canvas texture. For performance-critical animations with many frames, prefer a spritesheet with
AnimatedSprite
— it uses a single atlas texture and batches better on the GPU.
Related skills:
pixijs-scene-core-concepts
(scene graph basics),
pixijs-scene-sprite
(
AnimatedSprite
for spritesheet-based animation),
pixijs-assets
(
Assets.load
, caching, unloading),
pixijs-ticker
(frame timing),
pixijs-performance
(texture memory).
ts
import "pixi.js/gif";
import { GifSprite } from "pixi.js/gif";

const source = await Assets.load("animation.gif");

const gif = new GifSprite({
  source,
  autoPlay: true,
  loop: true,
  animationSpeed: 1,
});

gif.anchor.set(0.5);
gif.x = app.screen.width / 2;
gif.y = app.screen.height / 2;

app.stage.addChild(gif);
[!NOTE] GIF会将每一帧解码为单独的画布纹理。对于性能要求高且包含大量帧的动画,建议使用带
AnimatedSprite
的精灵表——它使用单个图集纹理,在GPU上的批处理效果更好。
相关技能:
pixijs-scene-core-concepts
(场景图基础)、
pixijs-scene-sprite
(基于精灵表动画的
AnimatedSprite
)、
pixijs-assets
Assets.load
、缓存、卸载)、
pixijs-ticker
(帧时序)、
pixijs-performance
(纹理内存)。

Constructor options

构造函数选项

GifSpriteOptions
extends
Omit<SpriteOptions, 'texture'>
;
texture
is managed internally (set from
source.textures[0]
and swapped per frame). All other
Sprite
options (
anchor
,
scale
,
tint
,
roundPixels
, etc.) are valid, and all
Container
options (
position
,
scale
,
tint
,
label
,
filters
,
zIndex
, etc.) are also valid here — see
skills/pixijs-scene-core-concepts/references/constructor-options.md
.
Leaf-specific options added by
GifSpriteOptions
:
OptionTypeDefaultDescription
source
GifSource
Required. The parsed GIF data returned by
Assets.load('file.gif')
. Can be shared across multiple
GifSprite
instances.
autoPlay
boolean
true
Start playback immediately on construction. If
false
, you must call
gif.play()
to begin.
loop
boolean
true
Repeat the animation on reaching the last frame. When
false
, the sprite stops at the final frame and fires
onComplete
.
animationSpeed
number
1
Multiplier on the GIF's native frame timing.
2
runs at double speed;
0.5
runs at half.
autoUpdate
boolean
true
Connect playback to
Ticker.shared
. Set to
false
to drive updates yourself via
gif.update(ticker)
.
fps
number
30
Fallback frame rate for GIFs that do not specify per-frame delays.
onComplete
() => void | null
null
Called when a non-looping animation reaches the last frame.
onLoop
() => void | null
null
Called each time a looping animation wraps around.
onFrameChange
(frame: number) => void | null
null
Called every time the displayed frame index changes.
scaleMode
SCALE_MODE
'linear'
Deprecated since 8.13.0 — pass
scaleMode
via
Assets.load(..., { data: { scaleMode } })
instead.
The constructor also accepts a bare
GifSource
as its sole argument (
new GifSprite(source)
), which is shorthand for
new GifSprite({ source })
using the defaults above.
GifSpriteOptions
继承自
Omit<SpriteOptions, 'texture'>
texture
由内部管理(从
source.textures[0]
设置,并随帧切换)。所有其他
Sprite
选项(
anchor
scale
tint
roundPixels
等)均有效,所有
Container
选项(
position
scale
tint
label
filters
zIndex
等)在此也有效——详见
skills/pixijs-scene-core-concepts/references/constructor-options.md
GifSpriteOptions
新增的叶子节点专属选项:
选项类型默认值描述
source
GifSource
必填项。
Assets.load('file.gif')
返回的已解析GIF数据。可在多个
GifSprite
实例之间共享。
autoPlay
boolean
true
构造完成后立即开始播放。若设为
false
,必须调用
gif.play()
才能启动。
loop
boolean
true
到达最后一帧时重复动画。设为
false
时,精灵会在最后一帧停止并触发
onComplete
animationSpeed
number
1
GIF原生帧时序的乘数。设为
2
表示两倍速播放;设为
0.5
表示半速播放。
autoUpdate
boolean
true
将播放连接到
Ticker.shared
。设为
false
可通过
gif.update(ticker)
自行驱动更新。
fps
number
30
未指定每帧延迟的GIF的 fallback 帧率。
onComplete
() => void | null
null
非循环动画到达最后一帧时触发。
onLoop
() => void | null
null
循环动画每次循环结束时触发。
onFrameChange
(frame: number) => void | null
null
显示的帧索引每次变化时触发。
scaleMode
SCALE_MODE
'linear'
自8.13.0版本起已废弃——请通过
Assets.load(..., { data: { scaleMode } })
传入
scaleMode
构造函数也可仅接受一个
GifSource
作为参数(
new GifSprite(source)
),这是使用上述默认值的
new GifSprite({ source })
的简写形式。

Core Patterns

核心模式

Setup and the side-effect import

设置与副作用导入

ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
import { GifSprite } from "pixi.js/gif";

const source = await Assets.load("animation.gif");
const gif = new GifSprite({ source });
pixi.js/gif
calls
extensions.add(GifAsset)
, registering
.gif
with the asset loader. Without it,
Assets.load
does not recognize GIF files.
GifSprite
and
GifSource
are exported from
pixi.js/gif
, not
pixi.js
.
Importing a named export from
pixi.js/gif
also triggers the side effect, so a bare
import 'pixi.js/gif'
is only needed when you don't import anything from that path.
ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
import { GifSprite } from "pixi.js/gif";

const source = await Assets.load("animation.gif");
const gif = new GifSprite({ source });
pixi.js/gif
会调用
extensions.add(GifAsset)
,将
.gif
注册到资源加载器中。如果不导入它,
Assets.load
将无法识别GIF文件。
GifSprite
GifSource
pixi.js/gif
导出,而非
pixi.js
pixi.js/gif
导入命名导出也会触发副作用,因此只有当你不从该路径导入任何内容时,才需要单独导入
import 'pixi.js/gif'

Playback control

播放控制

ts
const gif = new GifSprite({ source });

gif.play();
gif.stop();

gif.currentFrame = 5;
gif.animationSpeed = 2;
gif.animationSpeed = 0.5;

gif.playing; // read-only
gif.progress; // 0-1 playback position
gif.totalFrames; // number of frames
gif.duration; // total duration in ms
autoPlay: true
(default) starts playback immediately;
loop: true
(default) repeats.
animationSpeed
is a multiplier on the GIF's native frame timing.
currentFrame
is zero-based.
ts
const gif = new GifSprite({ source });

gif.play();
gif.stop();

gif.currentFrame = 5;
gif.animationSpeed = 2;
gif.animationSpeed = 0.5;

gif.playing; // 只读
gif.progress; // 播放进度(0-1)
gif.totalFrames; // 总帧数
gif.duration; // 总时长(毫秒)
autoPlay: true
(默认值)会立即开始播放;
loop: true
(默认值)会重复播放。
animationSpeed
是GIF原生帧时序的乘数。
currentFrame
从0开始计数。

Loading options

加载选项

ts
const source = await Assets.load({
  src: "animation.gif",
  data: {
    fps: 12,
    scaleMode: "nearest",
    resolution: 2,
  },
});

const fromDataUri = await Assets.load("data:image/gif;base64,R0lGODlh...");
Options in
data
are passed to
GifSource.from
.
fps
sets the fallback frame delay for GIFs that don't specify timing.
scaleMode
and
resolution
control the canvas textures created for each frame. The loader matches both
.gif
file extensions and
data:image/gif
URIs.
ts
const source = await Assets.load({
  src: "animation.gif",
  data: {
    fps: 12,
    scaleMode: "nearest",
    resolution: 2,
  },
});

const fromDataUri = await Assets.load("data:image/gif;base64,R0lGODlh...");
data
中的选项会传递给
GifSource.from
fps
为未指定时序的GIF设置 fallback 帧延迟。
scaleMode
resolution
控制为每一帧创建的画布纹理。加载器同时支持
.gif
文件扩展名和
data:image/gif
格式的URI。

Callbacks

回调函数

ts
const gif = new GifSprite({
  source,
  loop: false,
  onComplete: () => console.log("animation finished"),
  onLoop: () => console.log("loop completed"),
  onFrameChange: (frame) => console.log("now on frame", frame),
});
  • onComplete
    fires when a non-looping animation reaches the last frame.
  • onLoop
    fires each time a looping animation wraps around.
  • onFrameChange
    fires every time the displayed frame changes.
ts
const gif = new GifSprite({
  source,
  loop: false,
  onComplete: () => console.log("动画结束"),
  onLoop: () => console.log("循环完成"),
  onFrameChange: (frame) => console.log("当前帧", frame),
});
  • onComplete
    :非循环动画到达最后一帧时触发。
  • onLoop
    :循环动画每次循环结束时触发。
  • onFrameChange
    :显示的帧每次变化时触发。

Manual update mode

手动更新模式

ts
const gif = new GifSprite({ source, autoUpdate: false });

app.ticker.add((ticker) => {
  gif.update(ticker);
});
autoUpdate: false
disconnects from
Ticker.shared
. You call
gif.update(ticker)
yourself, passing any
Ticker
instance. Useful when animation should be driven by a private ticker (e.g., a pause-aware game ticker).
ts
const gif = new GifSprite({ source, autoUpdate: false });

app.ticker.add((ticker) => {
  gif.update(ticker);
});
autoUpdate: false
会断开与
Ticker.shared
的连接。你需要自行调用
gif.update(ticker)
,传入任意
Ticker
实例。当动画需要由私有ticker驱动时(例如支持暂停的游戏ticker),此模式非常有用。

Sharing source data and cloning

共享源数据与克隆

ts
const source = await Assets.load("animation.gif");

const gif1 = new GifSprite({ source, autoPlay: true });
const gif2 = new GifSprite({ source, autoPlay: false });

const gif3 = gif1.clone();
gif3.animationSpeed = 0.5;
GifSource
can be shared across multiple
GifSprite
instances; each sprite has independent playback state.
clone()
copies all playback settings but creates an independent instance.
ts
const source = await Assets.load("animation.gif");

const gif1 = new GifSprite({ source, autoPlay: true });
const gif2 = new GifSprite({ source, autoPlay: false });

const gif3 = gif1.clone();
gif3.animationSpeed = 0.5;
GifSource
可在多个
GifSprite
实例之间共享;每个精灵拥有独立的播放状态。
clone()
会复制所有播放设置,但创建一个独立的实例。

Common Mistakes

常见错误

[HIGH] Not importing pixi.js/gif

[高风险] 未导入pixi.js/gif

Wrong:
ts
import { Assets } from "pixi.js";
const gif = await Assets.load("animation.gif");
Correct:
ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
const source = await Assets.load("animation.gif");
The GIF loader extension must be registered before loading. Without the side-effect import, the loader does not recognize
.gif
files and the load either fails or returns raw data.
错误示例:
ts
import { Assets } from "pixi.js";
const gif = await Assets.load("animation.gif");
正确示例:
ts
import "pixi.js/gif";
import { Assets } from "pixi.js";
const source = await Assets.load("animation.gif");
必须先注册GIF加载器扩展,才能加载GIF。如果不导入副作用模块,加载器将无法识别
.gif
文件,加载操作要么失败,要么返回原始数据。

[MEDIUM] Expecting Assets.load to return a Texture

[中风险] 期望Assets.load返回Texture

Wrong:
ts
const texture = await Assets.load("animation.gif");
const sprite = new Sprite(texture);
Correct:
ts
const source = await Assets.load("animation.gif");
const gif = new GifSprite({ source });
Assets.load
on a GIF returns a
GifSource
containing frame textures and timing data. Pass the source to
GifSprite
; for a single still frame, read
source.textures[0]
.
错误示例:
ts
const texture = await Assets.load("animation.gif");
const sprite = new Sprite(texture);
正确示例:
ts
const source = await Assets.load("animation.gif");
const gif = new GifSprite({ source });
对GIF执行
Assets.load
会返回包含帧纹理和时序数据的
GifSource
。请将源传递给
GifSprite
;如果需要单张静态帧,可读取
source.textures[0]

[MEDIUM] GIF memory not released on destroy

[中风险] 销毁时未释放GIF内存

Wrong:
ts
gif.destroy();
// GifSource and frame textures remain in memory
Correct:
ts
gif.destroy(true);
// or
await Assets.unload("animation.gif");
GIF frames hold decoded pixel data as individual canvas textures.
gif.destroy()
(or
destroy(false)
) destroys the sprite but keeps the
GifSource
intact. Pass
true
to also destroy the source. For shared sources, only destroy when the last consumer is done, or call
Assets.unload
to let the asset cache handle it.
错误示例:
ts
gif.destroy();
// GifSource和帧纹理仍留在内存中
正确示例:
ts
gif.destroy(true);
// 或者
await Assets.unload("animation.gif");
GIF帧将解码后的像素数据存储为单独的画布纹理。
gif.destroy()
(或
destroy(false)
)会销毁精灵,但保留
GifSource
完整。传入
true
可同时销毁源。对于共享源,仅当最后一个使用者不再需要时才销毁,或者调用
Assets.unload
让资源缓存处理。

[LOW] Do not nest children inside a GifSprite

[低风险] 不要在GifSprite中嵌套子元素

GifSprite
extends
Sprite
, which sets
allowChildren = false
. It is a leaf. To group a GIF with other display objects, wrap them all in a plain
Container
:
ts
const group = new Container();
group.addChild(gif, label);
GifSprite
继承自
Sprite
,后者设置了
allowChildren = false
,因此它是叶子节点。如需将GIF与其他显示对象分组,请将它们全部包装在普通的
Container
中:
ts
const group = new Container();
group.addChild(gif, label);

API Reference

API参考