Why can't update access an objects img properties?

≡放荡痞女 提交于 2019-12-13 07:20:23

问题


I'm trying to create a simple JS game engine on my own.

Here's the code for one of the states.

var menuState = {
    //state variables
   menuBttn: {x: _canvas.width/2, y:_canvas.height/2, img: imageArray[2], over: false, click: function(){changeState(2);}},

    preload: function () {

    },

    update: function(){
        surface.clearRect(0, 0, _canvas.width, _canvas.height);
        for (var i = 0; i < menuAssets; i++){
        surface.drawImage(menuState.menuBttn.img , menuState.menuBttn.x, menuState.menuBttn.y);              
        console.log(menuState.menuBttn.x); //this shows that update CAN access properties of menuBttn
        }
    },

    exit: function(){

    },

};

However, when I run the state, the update function throws the error - "Failed to execute drawImage, value is not of type HTMLImageElement". I know that means that menuState.menuBttn.img is not an image().

But here's the code where imageArray(which is a global var) is defined.

var preloadState = {
    //state variables

    preload: function () {
        console.log("In preloadPreload..");

        for (var i=0; i < assetsArray.length; i++){

        imageArray[i] = new Image();
        imageArray[i].src = assetsArray[i];
        console.log("Loaded asset.." + i);
        }

        changeState(1);
    }

};

assetArray is just an array of strings that contain the source path.

So I guess my question is: Why isn't menuState.menuBttn.img an Image() object?

来源:https://stackoverflow.com/questions/41841512/why-cant-update-access-an-objects-img-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!