Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!