javascript - Canvas HTML 加载时间

标签 javascript html canvas

我尝试使用 HTML Canvas 制作游戏,但我遇到了问题。

当我用“window.onload”调用我的“init”函数时,我的程序没有加载任何图像。 Canvas 已创建,但图像不存在,当我在 chrome 控制台中提交我的函数时,图像出现......所以我想加载我的图像并在完成后执行该函数。

感谢帮助!

var requestAnimId;

// Initialisation
function init() {

    var tilemapCtx = new Canvas('tilemap', 800, 600, 1);

    var tilemap = new Tilemap("sand", tilemapCtx);

    requestAnimId = window.requestAnimationFrame(update);
}

// Boucle de rafraîchissement
function update() {

    requestAnimId = window.requestAnimationFrame(update);
}

window.onload = init;

这是瓷砖 map :

var Tilemap = function(map, canvas) {

for (var y = 0; y < 10; y++) {

    for (var x = 0; x < 10; x++) {
        // Création de la tile 
        this.image = new Image();
        // Définition de l'image  
        switch(tilemaps[map][y][x]) {
            case " ": 
                this.image.src = "assets/sand.png";
            break;
            case "#": 
                this.image.src = "assets/wall.png";
            break;
        } 
        // Affichage de l'image 
        //canvas.drawImage(this.image, tileX, tileY, tilesetWidth, tilesetHeight, x, y, 32, 32);
        canvas.drawImage(this.image, 32, 32);
    }
}

和 Canvas :

var Canvas = function(name, width, height, zIndex) {
this.canvas = window.document.createElement("canvas");
this.canvas.id = name;
this.canvas.style.position = "absolute";
this.canvas.width = width;
this.canvas.height = height;
this.canvas.style.zIndex = zIndex;
document.body.appendChild(this.canvas);

return this.canvas.getContext('2d');

最佳答案

请注意,对于您的图 block ,您只使用了两张图片。您使用将加载 100 张图像 的双循环。

一个问题是您创建了 100 张图像,但最终您只需要两张

现在您的图像未被绘制的原因是因为它们尚未被加载。在尝试绘制图像之前,您需要给图像加载时间。

在调用 init()

之前,您需要创建一个图像数组列表并确保它们已加载

This将确保在调用 init() 之前加载所有图像。

var len = pics.length;
var loadCounter = 0;
for(var i = 0; i < len; i++) {
    $(document.createElement(img)).attr('src', pics[i]).load(function() {
        alert(pics[i] + 'is loaded');
        loadCounter++;
        if(loadCounter === len) {
            alert("all are loaded");   
        }
    });
}

关于javascript - Canvas HTML 加载时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053023/

相关文章:

javascript - Bootstrap DateTimePicker - 选择月份(YYYY-MM 格式)

php - 同步旋转背景和标题

javascript - react : Trigger button click from array map by another child

javascript - 如果 <p contenteditable> 增长,则让 <div> 增长

javascript - 如何在 EaselJS 中更新径向渐变填充颜色

html - 如何将图像放在 Canvas 上其他绘图的后面?

javascript - HTML5、 Canvas 和 strokeRect : some lines too narrow and blurry

java - 在 tomcat 和 weblogic 上部署时的 JQuery 问题

JavaScript 突然无法读取值

javascript - Bootstrap 模式中的innerHTML