JavaScript图像永远不会完成.onload

时间:2015-08-07 00:44:54

标签: javascript html image function onload

新用户。

我正在使用JavaScript制作曲棍球游戏,我需要在调用main函数之前完成所有图像的加载,以避免闪烁。

使用了四张图片:skaterAmin.png,skaterBmin.png,goalieAmin.png,goalieBmin.png

我遇到了4个.onload函数中的2个。

loadSkaterImgAloadSkaterImgB都将更改为trueloadGoalieImgAloadGoalieImgB仍为false

还使用console.log()确认他们确实被卡住了

我还仔细检查了所有图片src'并且它们是正确的

//load images before main draw function to avoid flickering

var loadSkaterImgA = false;
var loadGoalieImgA = false;
var loadSkaterImgB = false;
var loadGoalieImgB = false;

function preloadSkaterImgA() {
    var skaterImgA = new Image();
    skaterImgA.onload = function() {
        completeSkaterImgA();
        return;
    }
    skaterImgA.src = 'skaterAmin.png';
    return skaterImgA;
}

function preloadGoalieImgA() {
    var goalieImgA = new Image();
    goalieImgA.onload = function() {
        completeGoalieImgA();
        return;
    }
    goalieImgA = 'goalieAmin.png';
    return goalieImgA;
}

function preloadSkaterImgB(){
    var skaterImgB = new Image();
    skaterImgB.onload = function() {
        completeSkaterImgB();
        return;
    }
    skaterImgB.src = 'skaterBmin.png';
    return skaterImgB;
}

function preloadGoalieImgB(){
    var goalieImgB = new Image();
    goalieImgB.onload = function() {
        completeGoalieImgB();
        return;
    }
    goalieImgB = 'goalieBmin.png';
    return goalieImgB;
}

function completeSkaterImgA(){
    loadSkaterImgA = true;
    return loadSkaterImgA;
}

function completeGoalieImgA(){
    loadGoalieImgA = true;
    return loadGoalieImgA;
}

function completeSkaterImgB(){
    loadSkaterImgB = true;
    return loadSkaterImgB;
}

function completeGoalieImgB(){
    loadGoalieImgB = true;
    return loadGoalieImgB;
}

preloadSkaterImgA();
preloadGoalieImgA();
preloadSkaterImgB();
preloadGoalieImgB();

感谢您阅读

1 个答案:

答案 0 :(得分:0)

你需要在DOM(等待加载所有图像)加载之后调用你的预加载方法:

window.onload = function () { 
    preloadSkaterImgA();
    preloadGoalieImgA();
    preloadSkaterImgB();
    preloadGoalieImgB();
 }