精灵无法在没有任何错误的情况下进行渲染



我正在尝试加载多个精灵并将它们显示在PIXI.js中。文件名包含在JSON清单中,我获取该清单,然后将其传递给加载器。尽管加载成功(我可以在检查器中看到请求(,但它们从未在PIXI阶段显示。代码包含在两个文件中。

background.js:

import * as PIXI from 'pixi.js';
import axios from 'axios';
const loader = PIXI.Loader.shared;
const ticker = PIXI.Ticker.shared;
const paintMovingSprite = ({ resource, container, surfaceWidth, surfaceHeight }) => {
let texture = new PIXI.Sprite(resource.texture);
let ratio = (surfaceHeight / texture.height / 3) * Math.random();
texture.width = texture.width * ratio + 50;
texture.height = texture.height * ratio + 50;
texture.x = Math.random() * surfaceWidth - texture.width / 2;
texture.y = Math.random() * surfaceHeight - texture.height / 2;

return texture;
};
const renderBackground = ({ fileNames, surfaceWidth, surfaceHeight }) => {
return new Promise((resolve, reject) => {
const container = new PIXI.Container();
loader.add(fileNames).load((_, resources) => {
Object.keys(resources).forEach(resource => {
container.addChild(
paintMovingSprite({ resource, surfaceWidth, surfaceHeight })
);
});
const testG = new PIXI.Graphics();
testG.beginFill(0xFFFF00);
testG.lineStyle(5, 0xFF0000);
testG.drawRect(0, 0, 300, 200);
console.log(container);
container.addChild(testG);
return resolve(container);
});
});
};
export { renderBackground };

有趣的是,测试矩形图形渲染成功,容器包含了它应该包含的所有子对象(每个图像一个(。

import * as PIXI from 'pixi.js';
import axios from 'axios';
import * as Menu from './menu.js';
import * as Background from './background.js';

PIXI.utils.sayHello();
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
backgroundColor: 0xffffff,
autoResize: true,
});
document.body.appendChild(app.view);
/* config */
app.renderer.backgroundColor = 0x33ff3f;
app.stage.sortableChildren = true;
let fileNames = null; 
const renderPage = () => {
axios.get('assets/asset-data.json').then((resp) => {
fileNames = resp.data['mix12'];

Background.renderBackground({
fileNames, 
surfaceWidth: app.renderer.width,
surfaceHeight: app.renderer.height,
}).then(container => {
// container object here looks correct and contains all the children
app.stage.addChild(container);
});
});
};
renderPage();

我是这个框架的新手,所以可能缺少一些基本的东西。

谢谢。

代码中的错误似乎就在这里:

Object.keys(resources).forEach(resource => {
container.addChild(
paintMovingSprite({ resource, surfaceWidth, surfaceHeight })
);
});

resource只是一个键——它不是您想要的实际资源——它应该是:resources[resource]

更好的做法是将resource重命名为key,这样我们就可以看到发生了什么:

Object.keys(resources).forEach(key => {
let resource = resources[key];
container.addChild(
paintMovingSprite({ resource, surfaceWidth, surfaceHeight })
);
});

请参阅此处关于Object.keys(myObj).forEach(...的更多解释:如何在一个以对象为成员的纯JavaScript对象中循环?

下次当您在使用PIXI(或任何其他库(中的某些功能时遇到问题时,我建议您尝试在最简单的示例代码中使用所述功能。我的意思是:不容易理解/调试"隐藏"在Promises和回调(箭头函数(等几层下面的东西:(

相关内容

最新更新