You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PixiJS Animated Sprite仅显示首帧无法播放问题求助

问题根源

你只在初始化时调用了一次this.renderer.render(this.stage),PixiJS的AnimatedSprite会自动切换纹理,但如果没有持续的渲染循环,画布不会更新显示新的帧,所以动画看起来没动。

修复方案

用PixiJS的PIXI.Ticker创建渲染循环,它会同步浏览器刷新频率自动触发渲染:

  1. 移除playAnimation里的单次render调用
  2. 初始化Ticker并绑定渲染逻辑
  3. 组件销毁时清理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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:39:45