如何通过数组中的子画面位置递增?

问题描述 投票:-1回答:1

所以我有一个带有要显示的精灵的字符串数组:

var lts = [
    "letterA",
    "letterB",
    "letterC",
    "letterD",
    "letterE",
    "letterF"
];

在我的assets.js中,我加载了它们:

function loadAssets(callback){

    function loadSprite(fileName){
        assetsStillLoading++;

        let spriteImage = new Image();
        spriteImage.src = "assets/sprites/" + fileName;

        spriteImage.onload = function()
        {
            assetsStillLoading--;
        }

        return spriteImage;
    }
    sprites.background = loadSprite('spr_background_pink.png');

    sprites.letterA = loadSprite('/Letters/letter_A.png');
    sprites.letterB = loadSprite('/Letters/letter_B.png');
    sprites.letterC = loadSprite('/Letters/letter_C.png');
    sprites.letterD = loadSprite('/Letters/letter_D.png');
    sprites.letterE = loadSprite('/Letters/letter_E.png');
    sprites.letterF = loadSprite('/Letters/letter_F.png');
}

现在,我希望能够遍历此字母选项来选择正确的字母,如下所示:

letterNo = letterNo + 1;

var string = "sprites." + lts[letterNo];
console.log("sprite loading:" + string);
this.sprite = string;

但是当我尝试时会得到:

sprites.letterB在调试器中,这是我要加载的精灵,但它不喜欢它:

TypeError:CanvasRenderingContext2D.drawImage的参数1无法转换为以下任何一种:HTMLImageElement,SVGImageElement,HTMLCanvasElement,HTMLVideoElement,ImageBitmap。

我该如何使它正常工作?

javascript arrays html5-canvas sprite
1个回答
0
投票

"sprites.letterB"只是一个与sprites对象无关的字符串。如果要访问Sprites对象中的键,请使用方括号表示法:sprites[lts[letterNo]]

© www.soinside.com 2019 - 2024. All rights reserved.