简体   繁体   English

画布根本不渲染图像

[英]Canvas not rendering images at all

I have an array of enemies sent from the server and I am recreating them because they were serialized. 我从服务器发送了一系列敌人,由于它们已被序列化,因此我正在重新创建它们。 After, I'm trying to get them to render on the canvas, but that isn't working for some reason. 之后,我试图让它们在画布上渲染,但是由于某种原因,它不起作用。

for (var i = 0; i < enemies.length; i++) { // recreate each enemy and render it
    var image = new Image();
    var currentFish = new Fish();
    for (var key in enemies[i]) { // copying properties to object that has the necessary methods
        if (enemies[i].hasOwnProperty(key)) {
            currentFish[key] = enemies[i][key];
        }
    }
    image.src = currentFish.icon;
    image.onload = function () {
        ctx.drawImage(image, currentFish.position.x, currentFish.position.y);
    };
    ctx.fillText('Drone', 250, 200);    
}

I think the issue is that image.onload is not called until after or in between frames so it isn't seen. 我认为问题在于image.onload直到帧之后或帧之间才被调用,因此它不可见。 I'm not sure how to work around this. 我不确定如何解决此问题。

Edit: 编辑:

I forgot to mention that I'm using requestAnimationFrame to handle rendering the canvas, so I don't know when the frame is going to be rendered. 我忘了提到我正在使用requestAnimationFrame来处理画布的渲染,因此我不知道何时渲染帧。

The problem is that your outside for loop is overwriting the image variable with each loop (before the image can be loaded and drawn). 问题是您的外部for循环正在每个循环中覆盖image变量(可以加载和绘制图像之前)。

Try this alternative image loader which preloads all images into imgs[] and then calls start(): 试试这个替代的图像加载器,它将所有图像预加载到imgs []中,然后调用start():

// image loader

var imageURLs = [];  // put the paths to your images here
var imagesOK = 0;
var imgs = [];
imageURLs.push("");
loadAllImages(start);

function loadAllImages(callback) {
    for (var i = 0; i < imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function() { 
            imagesOK++; 
            if (imagesOK >= imageURLs.length) {
                callback();
            }
        };
        img.onerror = function() {alert("image load failed");} 
        img.crossOrigin = "anonymous";
        img.src = imageURLs[i];
    }      
}

function start() {

    // imgs[] holds fully loaded images
    // imgs[] is in the same order as imageURLs[]

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM