0

I'm trying to generate multiple canvas and draw on them in loop.

When I execute the code all canvas generate properly, but only the last one have rectangle on it.

for(var i = 0; i < canvasNumber; i++) {
    $(".canvas-container")[0].innerHTML += `<canvas class="canva${i}"></canvas>`;
    $(`.canva${i}`)[0].width = window.innerWidth/5;
    $(`.canva${i}`)[0].height = window.innerHeight/5;
    let cc = $(`.canva${i}`)[0].getContext("2d");
    cc.fillRect(30*i,20,200,100);
}

enter image description here

Ali Kianoor
  • 1,167
  • 9
  • 18
Omicron
  • 365
  • 4
  • 9
  • 1
    Does this answer your question? [Appending Child resets previous appended element value on JavaScript](https://stackoverflow.com/questions/28583253/appending-child-resets-previous-appended-element-value-on-javascript) – Sree.Bh Jun 18 '20 at 18:30

1 Answers1

1

As mentioned in @prog1011's answer:

Below DOM element properties can cause browser to perform a reflow operation

  • innerHTML
  • offsetParent
  • style
  • scrollTop

innerHTML will only trigger a reflow when setting it changes the DOM.

innerHTML changes the HTML of an object which certainly can affect size and position and will trigger at least a partial reflow.

See the reference link

So instead of innerHTML use append as below:

const canvasNumber = 4;
const width = window.innerWidth / 5;
const height = window.innerHeight / 5;

for (var i = 0; i < canvasNumber; i++) {
  $(".canvas-container").append($(`<canvas class="canvas"></canvas>`));
  const $canvas = $('.canvas').eq(i)[0];
  $canvas.width = width;
  $canvas.height = height;
  const cc = $canvas.getContext("2d");
  cc.fillRect(30 * i, 20, 200, 100);
}
.canvas {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="canvas-container"></div>
Sree.Bh
  • 1,751
  • 2
  • 19
  • 25
  • 1
    "Reflow" has nothing to do with the matter here. Reflow, a.k.a "recalc" is when the browser as to recalculate the position of all elements in the page, because one of the elements did move, but that doesn't change any content. – Kaiido Jun 19 '20 at 01:41