我正在开发一个在画布上加载,渲染和刷新图像的系统 对于我的javascript引擎项目,但当我使用img.onload时,它才能在我能够设置img源之前执行
主要功能:
function addImgToList(canvas, url, sw, sh) {
TempVar = {s: CheckSlots(canvas, 0)
};
that = this.TempVar;
CurrentGFXElements[canvas].images[TempVar.s] = {
img: new Image(),
sw: sw,
sh: sh,
sprites: [],
active: true,
lx: 0, // last x
ly: 0, // last y
ew: 0,
eh: 0,
animations: 0
};
/*error calculations begins before img has been loaded
*/
CurrentGFXElements[canvas].images[TempVar.s].img.onload = function (TempVar) {
calcSprites(canvas, TempVar.s, sw, sh);
} (TempVar);
//CurrentGFXElements[canvas].images[TempVar.s].img.src = url;
CurrentGFXElements[canvas].indexList[TempVar.s][0] = 1;
return TempVar.s;}
注意:我知道设置src的行已注释
计算功能:
function calcSprites(canvas, slot, sw, sh, height) {
TempVar = {
h: CurrentGFXElements[canvas].images[slot].img.height,
w: CurrentGFXElements[canvas].images[slot].img.width,
x: 0,
y: 0,
s: slot
};
TempVar.columns = TempVar.w / sw;
TempVar.rows = TempVar.h / sh;
TempVar.sprites = TempVar.columns * TempVar.rows;
console.log(TempVar);
for (i = 0; i < TempVar.sprites; i++) {
CurrentGFXElements[canvas].images[slot].sprites[i] = [[TempVar.x, TempVar.y]];
console.log(CurrentGFXElements[canvas].images[slot].sprites[i]);
TempVar.x += CurrentGFXElements[canvas].images[slot].sw;
if (TempVar.x >= (CurrentGFXElements[canvas].images[slot].sw * TempVar.columns)) {
TempVar.x = 0;
TempVar.y += CurrentGFXElements[canvas].images[slot].sh;
}
}
return TempVar;}
可以在这里查看完整的文件:(此链接不是24/7全天候)(跳过顶部代码的注释部分)
答案 0 :(得分:0)
我发现每当你将参数传递给一个匿名函数时会出现错误,如果你为onload分配一个函数,函数会自动激活这个错误:
//will activate instantly
img.onload = someFunction();
//same as above
img onload = function (argument) {//insert code}(argument_to_pass);
//these will work without problems
img.onload = someFunction; //this one should work but not 100% sure
img.onload = function () {//insert code}