PIXI Sprite加载异常:页面刷新后图片无法显示的修复方案咨询
问题修复方案
你的问题核心是图片加载是异步过程,当前代码在创建Sprite后立刻调用resize,此时纹理还没加载完成,Sprite的宽高是默认的1x1,导致画布被缩到1像素。必须等图片加载完成后再执行尺寸调整逻辑。
具体修复步骤
1. 等待纹理加载完成再调整大小
PIXI的Texture.from()加载远程图片时,纹理初始状态未就绪,你可以通过监听纹理的update事件(加载完成后触发)来执行resize操作。同时要注意销毁旧的PIXI应用和纹理,避免内存泄漏。
2. 优化ngOnChanges触发逻辑
避免每次ngOnChanges触发都重复创建应用,先判断urlInputImage是否有效且发生变化,再执行绘制逻辑。
修改后的完整代码
import { Component, Input, OnChanges, OnDestroy, SimpleChanges } from '@angular/core'; import * as PIXI from 'pixi.js'; export class ImageComponent implements OnChanges, OnDestroy { @Input() urlInputImage: string; public app: PIXI.Application | null = null; private currentTexture: PIXI.Texture | null = null; ngOnChanges(changes: SimpleChanges) { // 仅当urlInputImage变化且有有效值时执行绘制 if (changes['urlInputImage'] && this.urlInputImage) { this.drawImage(); } } private removeAllChildNodes(parent: HTMLElement) { while (parent.firstChild) { parent.removeChild(parent.firstChild); } } private drawImage(): void { const frame = document.querySelector('#frame') as HTMLElement; if (!frame) return; // 销毁旧资源,避免内存泄漏 this.destroy(); this.app = new PIXI.Application({ backgroundColor: 0xffffff, }); const container = new PIXI.Container(); this.app.stage.addChild(container); frame.appendChild(this.app.view); // 创建纹理并监听加载完成事件 this.currentTexture = PIXI.Texture.from(this.urlInputImage); const pic = new PIXI.Sprite(this.currentTexture); container.addChild(pic); // 处理纹理加载完成后的逻辑 const handleTextureReady = () => { this.resize(pic); // 移除监听,避免重复触发 this.currentTexture?.off('update', handleTextureReady); }; // 如果纹理已缓存(比如重复加载同一张图),直接执行resize if (this.currentTexture.valid) { handleTextureReady(); } else { this.currentTexture.on('update', handleTextureReady); } } private resize(pic: PIXI.Sprite) { const w = pic.width; const h = pic.height; if (w <= 1 || h <= 1) return; // 跳过无效尺寸 // 调整画布样式尺寸 this.app?.renderer.view.style.width = `${w}px`; this.app?.renderer.view.style.height = `${h}px`; // 调整渲染器实际尺寸 this.app?.renderer.resize(w, h); } destroy() { // 销毁纹理 this.currentTexture?.destroy(true); this.currentTexture = null; // 销毁PIXI应用 this.app?.destroy(true); this.app = null; } ngOnDestroy(): void { this.destroy(); } }
额外优化说明
- 新增
SimpleChanges参数,精准判断输入属性的变化情况 - 完善资源销毁逻辑,防止内存泄漏
- 增加无效尺寸判断,避免异常场景
- 兼容纹理已缓存的情况,提升重复加载时的体验
内容的提问来源于stack exchange,提问作者user1568064
相关产品推荐
相关产品推荐

