Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

480
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda