我有一些看起来像这样的代码:
createEntity = function (imageSource, baseX, baseY) {
tmpIndex = images.length;
images[tmpIndex] = new Image();
entities[tmpIndex] = new Entity;
images[tmpIndex].onload = function () {
entities[tmpIndex].ready = true;
// How do I get the line above to use the value of tmpIndex
// that existed when it was created?
// That is to say, I want the images[1].onload function to
// change entities[1].ready, not entities[4].ready
// (assuming I created 5 objects sequentially
// before any images finished loading)
}
images[tmpIndex].src = imageSource;
entities[tmpIndex].x = baseX;
entities[tmpIndex].y = baseY;
}
createEntity("images/background.png", 0, 0);
createEntity("images/pawn1.png",0,0);
createEntity("images/pawn2.png",30,30);
createEntity("images/pawn3.png",60,60);
createEntity("images/pawn4.png",90,90);
问题是,当我依次加载所有5张图像时,如上面的代码所示,我的onload函数使用当前值tmpIndex触发,而不是函数创建时存在的值。是否有一种简单的方法可以正确地切换entries [somenumber] .ready?
您需要声明tmpIndex
为局部变量。要进行此更改
tmpIndex = images.length;
到
var tmpIndex = images.length;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句