'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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
