在for循环中绘制图像集的HTML5 Canvas仅绘制最后一个迭代图像集

我正在尝试使用for循环内的图像加载器绘制图像。它仅在最后一次迭代时绘制所有图像。


在控制台中,它不显示draw -> 0或draw -> 1仅显示draw -> 2


谢谢你的帮助!!


这是我的代码块:


        // For every player run iteration

        var pos="";

        var iter="";

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

            // Position for players on account screen


            if(i == 0){ pos = "61px"; iter = 0; console.log("pos 0 -> " + iter);}

            if(i == 1){ pos = "168px"; iter = 1; console.log("pos 1 -> " + iter);}

            if(i == 2){ pos = "275px"; iter = 2; console.log("pos 2 -> " + iter);}

            console.log(i);

            console.log("pos -> " + pos);

            console.log("iter -> " + iter);

            // Gets player name from string

            let player = item[i].match( /([A-Z])\w+/g );


            // Create player div for mouse interaction

            let player_el = $('<div class="cursor player" id="player'+ player +'"></div>');

            $("#can_wrapper").append(player_el);

            $("#player"+ player).css({"position": "absolute", "height": "50px", "width": "50px", "left": ""+ pos +"", "top": "271px", "cursor": "grab", "cursor": "-webkit-grab"});


            // Get player name for hover action

            let player_name_el = player;

            document.styleSheets[0].addRule('#player'+ player +':hover::after','content: "'+player_name_el+'";');


            /**

             * Promisify loading an image

             * @param {String} imagePath The web location of the image

             * @returns {Promise} A Promise that will resolve to an Image

             */

            function loadImage(imagePath) {

                return new Promise((resolve, reject) => {

                    let image = new Image();

                    image.addEventListener("load", () => {

                        resolve(image);

                    });

                });

        }


动漫人物
浏览 336回答 1
1回答

幕布斯7119047

我建议您function loadImage跳出循环圈如果您使用let代替var并将pos和iter的声明移到for循环中,那么它应该可以工作function loadImage(imagePath) {&nbsp; &nbsp; return new Promise((resolve, reject) => {&nbsp; &nbsp; &nbsp; &nbsp; let image = new Image();&nbsp; &nbsp; &nbsp; &nbsp; image.addEventListener("load", () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(image);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; image.addEventListener("error", (err) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reject(err);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; image.src = '../interface/images/body/' + imagePath;&nbsp; &nbsp; });}for (let i = 0; i < item.length; ++i) {&nbsp; &nbsp; let pos="";&nbsp; &nbsp; let iter="";&nbsp; &nbsp; // rest of your code remains unchanged}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript