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

Phaser 3程序化创建SVG动画报错:无法读取undefined的texture属性

问题分析与解决方案

错误根源

报错Uncaught TypeError: Cannot read properties of undefined (reading 'texture'),以及动画停留在第一帧的问题,核心原因是动画帧与图集帧的索引不匹配,且动画配置未正确注册到Phaser中:

  • 调试中动画索引从1开始,但Phaser图集的帧默认是0-based编号,导致找不到对应帧,animationFrame.frame变为undefined;
  • 代码中未将动画JSON配置注册到Phaser的动画管理器,Sprite无法识别目标动画的帧定义。

修复步骤

1. 注册动画配置

在加载图集前,先将动画JSON注册到全局动画管理器,确保Sprite能识别目标动画:

const atlasJson = this.cache.json.get('atlas-json');
const animationJson = this.cache.json.get('animation-json');

// 注册动画到Phaser全局动画管理器
this.anims.fromJSON(animationJson);

2. 修正动画帧索引

将动画配置中的1-based帧索引改为0-based,与Phaser图集的帧编号对齐:

// 遍历修正所有动画的帧索引
animationJson.anims.forEach(anim => {
    anim.frames = anim.frames.map(frame => {
        // 处理数字类型帧索引
        if (typeof frame === 'number') {
            return frame - 1;
        }
        // 处理字符串类型帧名称(如"frame1"改为"frame0")
        else if (typeof frame === 'string') {
            return frame.replace(/(\d+)/, match => parseInt(match) - 1);
        }
        return frame;
    });
});

3. 规范Sprite创建与动画调用

创建Sprite时传入图集名称字符串(而非texture对象),并确保动画注册完成后再调用play():

image.onload = () => {
    context.drawImage(image, 0, 0);
    URL.revokeObjectURL(svgBlobUrl);
    // 添加图集到纹理管理器
    this.textures.addAtlas('atlas', image, atlasJson);
    // 传入图集名称创建Sprite
    const sprite = this.add.sprite(100, 100, 'atlas');
    // 播放已注册的动画
    sprite.play('do_stuff');
};

额外检查点

  • 验证图集JSON中的帧名称/索引与动画JSON完全匹配;
  • 通过this.textures.get('atlas').getFrames()检查图集帧是否正确加载,确认帧数量与索引符合预期;
  • 确保SVG生成的图片完整渲染了所有帧,无缺失或偏移。

内容的提问来源于stack exchange,提问作者s1300045

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:05:22