PixiJS Animated Sprite仅显示首帧无法播放问题求助
问题根源
你只在初始化时调用了一次this.renderer.render(this.stage),PixiJS的AnimatedSprite会自动切换纹理,但如果没有持续的渲染循环,画布不会更新显示新的帧,所以动画看起来没动。
修复方案
用PixiJS的PIXI.Ticker创建渲染循环,它会同步浏览器刷新频率自动触发渲染:
- 移除
playAnimation里的单次render调用 - 初始化Ticker并绑定渲染逻辑
- 组件销毁时清理Ticker避免内存泄漏
修改后的完整代码:
import { Component, ElementRef, ViewChild, OnDestroy } from '@angular/core'; import * as PIXI from 'pixi.js'; @Component({ // 你的组件元数据 }) export class YourComponent implements OnDestroy { @ViewChild('canvas') canvas!: ElementRef; renderer!: PIXI.Renderer; stage = new PIXI.Container(); sheet!: PIXI.Spritesheet; private ticker: PIXI.Ticker; constructor() { this.ticker = PIXI.Ticker.shared; } ngAfterViewInit() { this.renderer = PIXI.autoDetectRenderer(); this.canvas.nativeElement.appendChild(this.renderer.view); this.renderer.resize(this.canvas.nativeElement.offsetHeight, this.canvas.nativeElement.offsetWidth); this.renderer.backgroundColor = 0xFFFFFF; this.renderer.clearBeforeRender = true; // 启动渲染循环 this.ticker.add(() => { this.renderer.render(this.stage); }); PIXI.Loader.shared.add("assets/animation/attack.json").load(() => { this.sheet = PIXI.Loader.shared.resources["assets/animation/attack.json"].spritesheet; this.playAnimation(); }); } playAnimation() { this.stage.addChild(new DBackground()); const animatedSprite = new PIXI.AnimatedSprite(this.sheet.animations["attack1"]); animatedSprite.animationSpeed = 0.5; // 可调低速度让动画更直观 animatedSprite.position.set(100, 100); // 可选:设置循环模式,默认loop=true,设为false则只播放一次 // animatedSprite.loop = true; this.stage.addChild(animatedSprite); animatedSprite.play(); } ngOnDestroy() { // 组件销毁时移除Ticker监听 this.ticker.remove(() => { this.renderer.render(this.stage); }); // 清理渲染器和舞台资源 this.renderer.destroy(); this.stage.destroy(); } }
额外检查点
animationSpeed设为1可能速度过快导致视觉不明显,建议先设为0.5测试- 确认
AnimatedSprite的loop属性符合预期,默认是循环播放 - 确保精灵表图片
attack.png和attack.json在同一目录下,路径正确
内容的提问来源于stack exchange,提问作者Lymn
相关产品推荐
相关产品推荐

