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

488
Visualizações
How do i do to make wait the program untile an image is load ? (java script)

I have recently started to learn html and i'm currently working on java script. My problem is that i would to stop the program until a image as been load for, after that draw the image on a canvas (because if the image is not load and i want to draw it on a canvas, nothing would be display).

Here's my code (put in one file) :

<html>
    <head>
        <title>dog food</title>
        <link rel = "icon" href = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQudx87gpctKJdgDyq5DpVlb12fI3_7XgbfXw&usqp=CAU">
        <style>
            canvas.GameWindow {
                display : block;
                margin-left : auto;
                margin-right : auto;
            }
        </style>
    </head>
    <body>
        <canvas width = 600 height = 350 class = GameWindow>Sorry but the canvas is not taken by your web browser</canvas>
        
        <script>
            var canvas = document.querySelector('canvas');
            var ctx = canvas.getContext('2d');
            
            //initialize canvas
            /*ctx.fillStyle = 'black';
             ctx.fillRect(0, 0, 600, 350);*/
            
            //create function
            function drawAnImage(positionX,positionY,width,height,image) {
                ctx.drawImage(image, positionX, positionY, width, height);
                console.log("an image has been drawn");
            };
            var img = new Image();
            img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQudx87gpctKJdgDyq5DpVlb12fI3_7XgbfXw&usqp=CAU";
            img.onload = function() {
                console.log("image load");
            };
            drawAnImage(0,0,100,100,img);
        </script>
    </body>
</html>

Actually when i run the code, nothing is display on the canvas because the image is load after i call the drawAnImage function.

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

0

Wait for it to load with a callback:

img.onload = function () {
    drawImage(0, 0, 100, 100, img);
};

You can also do something if there was an error loading it:

img.onerror = function () {
    alert("Oh no an error!");
};

Here it is with ES6 arrow functions and addEventListener:

img.addEventListener("load", () => {
    drawImage(0, 0, 100, 100, img);
});

img.addEventListener("error", () => {
    alert("Oh no an error!");
});
about 4 years ago · Juan Pablo Isaza Relatório

0

So i finaly use this little algorithm for image loading :

const imageToLoad = [];
                var totalImage = imageToLoad.length;
                let imageLoad = [];
                
                for (var i = 0;i<totalImage;i++) {
                    var img = new Image();
                    img.src = imageToLoad[i];
                    imageLoad.push(img);
                    img.onload = function() {
                        if (i == totalImage) {
                            //here i start my game loop
                            gameLoop(imageLoad);
                        };
                    };  
                };

So what values is for? The first valu imageToLoad is where you would put the images you want to use and imageLoad is where you would find your loaded images. Finaly, for the peoples interested in the algorithm, the algorithm would every time an image is load see if it the last image to load, if yes, the algorithm would start in my case the gameloop of the game.

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