Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
Javascript image width is 0 on load

I have this code for loading several images:

    const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];

function imageLoaded(i){
    imageCount--;
    if(imageCount == 0){
        window.TILEATLAS = assets[0];

        load();
    }
}

function loadAssets(){
    for(let i = 0, len = imageCount; i < len; i++){

        let image = new Image();

        image.src = imageURLS[i];
        assets.push(image);

        image.onload = imageLoaded(image);
    }
}

onload = loadAssets();

but when I try to access the images in the load() functions, it says the width and height are 0, for me indicating the images aren't finished loading, but they should be? I'm dumbfounded...

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is this line:

image.onload = imageLoaded(image);

Because you have the parenthesis, Javascript calls the function immediately and expects it to return the result that will be passed to the onload You need something like this:

const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];

function imageLoaded(){
    var i = this
    imageCount--;
    if(imageCount == 0){
        window.TILEATLAS = assets[0];

        load();
    }
}

function loadAssets(){
    for(let i = 0, len = imageCount; i < len; i++){

        let image = new Image();

        image.src = imageURLS[i];
        assets.push(image);

        image.onload = imageLoaded.bind(image);
    }
}

onload = loadAssets();

The bind function sets the value of this in the function to the argument. This way, it won't call the function, but create it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda