画布精灵图像仅在页面刷新后加载

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

我已经阅读了之前的文章,并且我知道图像最初没有被加载,因为我在加载之前绘制它,并且当我刷新它时,因为浏览器缓存了它绘制的图像。

首先,我有一个

Spritesheet
课程:

class Spritesheet
{
    constructor(filename, rows, cols, x, y)
    {
        this.filename  = `./game/static/img/${filename}`;

        this.rows = rows;
        this.cols = cols;
    
        this.x = x;
        this.y = y;
    
        this.spritesheet = new Image();
        this.spritesheet.onload = loadImages(this);
    }

    load()
    {
        this.spritesheet.src = this.filename;
        this.width = this.spritesheet.width / this.rows;
        this.height = this.spritesheet.height / this.cols;
    }

}

然后我有

loadImages
函数调用方法
load(spritesheet)
:

function loadImages(spritesheet)
{
    spritesheet.load();
    if (--numOfImages <= 0) loadGame();
    
}

在我的

window.onload
调用中,我有一个名为
preloadStatic()
的函数,它为游戏使用的某些 Sprite 填充 2 个数组:

function preloadStatic()
{
    var wallSpritesCount = 4;
    var floorSpritesCount = 10;

    numOfImages = wallSpritesCount + floorSpritesCount;
    
    for (let i = 0; i < wallSpritesCount; i++) {
        let filename = `wall/brick_gray_${i}.png`;
        let spritesheet = new Spritesheet(filename, 1, 1, 0, 0);
        wallSprites.push(spritesheet);
    }

    for (let i = 0; i < floorSpritesCount; i++) {
        let filename = `floor/white_marble_${i}.png`;
        let spritesheet = new Spritesheet(filename, 1, 1, 0, 0);
        floorSprites.push(spritesheet);
    }
}

但精灵仅在页面刷新后加载。

我使用它的逻辑是,当窗口加载时,它会预加载静态文件并设置变量

numOfImages
,当它循环遍历我需要在
Spritesheet
构造函数中加载的所有可能的精灵时,它会设置一个
new Image()
然后调用
onload
方法。然后在
onload
方法中调用
Spritesheet.load()
,将图像的来源设置为文件名。一旦每个
Spritesheet
被调用一次,变量
numOfImages
就会递减到 0,然后加载游戏。但这仅在刷新页面时有效。

抱歉,我问了一个以前被问过的问题,但我找不到解决方案,我尝试使用已多次描述的

onload
方法。感谢您阅读本文。

javascript html html5-canvas
1个回答
0
投票
  1. 您立即在构造函数中运行
    loadImage(this)
  2. 当您设置
    src
    时,您的图像将开始加载,因此您无法在
    load
    功能中执行此操作
class Spritesheet
{
    constructor(filename, rows, cols, x, y)
    {
        this.filename  = `./game/static/img/${filename}`;

        this.rows = rows;
        this.cols = cols;
    
        this.x = x;
        this.y = y;
    
        this.spritesheet = new Image();
        // added `() => `
        this.spritesheet.onload = () => loadImages(this);
        // added line below
        this.spritesheet.src = this.filename;
    }

    load()
    {
        // removed this.spritesheet.src = this.filename;
        this.width = this.spritesheet.width / this.rows;
        this.height = this.spritesheet.height / this.cols;
    }

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