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

201
Vistas
JavaScript: HTML Canvas generated from inside loop is not drawn

I have a setup where several HTML Canvas images are drawn from a JavaScript for loop (actually, two nested loops, but one is enough for illustrating the problem). All Canvases are generated (I see them in the generated HTML), but only some of them do actually contain the image I want to have.

In the (much simplified) example below, I am drawing a blue rectangle on each of the two canvases; but actually, only the second one is shown. I would be glad if someone could point me towards why this is the case. Let me add that I am pretty new to JavaScript, so besides a recipe of how to do it, also an explanation of why I see what I see is appreciated.

<!DOCTYPE html>
<html>
   <head>
      <title>HTML Document</title>
   </head>
   <body>
      <p>This is demo text.</p>
      <div id="test"></div>
      <script>
        window.onload = function () {

          const div = document.getElementById("test");

          for (i=0; i < 2; i++) {

            div.innerHTML += `<h3>i = ${i}</h3>`;

            var canvas = document.createElement("canvas");
            div.appendChild(canvas);
            canvas.width = 200;
            canvas.height = 50;

            var ctx = canvas.getContext("2d");
            ctx.fillStyle = 'rgb(10,10,100)';
            ctx.fillRect(10, 10, 100, 100);
          }
        }
      </script>
   </body>
</html>

about 4 years ago · Juan Pablo Isaza
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