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

202
Visualizações
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 à 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