当我将纹理加载到精灵中,然后询问精灵的宽度时,我得到的值为 1。只有经过动画循环几次后,宽度才有效。 有没有可靠的方法来检查加载纹理的尺寸?
var stage = new PIXI.Stage(0x66FF99);
var renderer = new PIXI.CanvasRenderer(800, 600);
document.body.appendChild(renderer.view);
var texture = PIXI.Texture.fromImage("stone.png");
var stone = new PIXI.Sprite(texture);
console.log(stone.width + ', ' + stone.height);
stage.addChild(stone);
console.log(stone.width + ', ' + stone.height);
requestAnimFrame( animate );
console.log(stone.width + ', ' + stone.height);
renderer.render(stage);
console.log(stone.width + ', ' + stone.height);
所有这些console.log()
记录“1, 1”,即使它应该是 128, 128。如果我把console.log()
放在动画循环中,它确实开始输出 128, 128。
是的! 这是因为纹理的图像还没有加载,所以它不知道它的宽度和高度是多少:/
从这个意义上说,它的行为与普通的 HTML 图像完全一样。
我一直在解决这个问题的方法是使用 assetLoader 来预加载我的图像。 这样,当我像这样创建纹理时,宽度和高度始终设置正确:
var assetsToLoad = [ "stone.png"];
// create a new loader
loader = new PIXI.AssetLoader(assetsToLoad);
// use callback
loader.onComplete = onAssetsLoaded
//begin load
loader.load();
function onAssetsLoaded()
{
var texture = PIXI.Texture.fromImage("stone.png");
var sprite = new PIXI.Sprite(texture);
// this will log the correct width and height as the image was preloaded into the pixi.js cache
console.log(stone.width + ', ' + stone.height);
}
另一种方法是将事件侦听器添加到您的纹理中。 当图像加载完毕后,它会发送一个“更新”事件。
var texture = PIXI.Texture.fromImage("stone.png");
var sprite = new PIXI.Sprite(texture);
if(texture.baseTexture.hasLoaded)
{
// this will log the correct width and height as the image has already loaded
console.log(stone.width + ', ' + stone.height);
}
else
{
texture.addEventListener("update", onTextureUpdate)
}
function onTextureUpdate()
{
// this will log the correct width and height as the image has loaded
console.log(stone.width + ', ' + stone.height);
}
希望有帮助:)
也可以做这样的事情: https :
更改 setTexture 函数以验证是否设置了宽度和高度
由于关闭后没有任何近期活动,因此该线程已自动锁定。 请为相关错误打开一个新问题。
最有用的评论
是的! 这是因为纹理的图像还没有加载,所以它不知道它的宽度和高度是多少:/
从这个意义上说,它的行为与普通的 HTML 图像完全一样。
我一直在解决这个问题的方法是使用 assetLoader 来预加载我的图像。 这样,当我像这样创建纹理时,宽度和高度始终设置正确:
另一种方法是将事件侦听器添加到您的纹理中。 当图像加载完毕后,它会发送一个“更新”事件。
希望有帮助:)