0

How can I use for in JavaScript to create more canvas object with less code

for (I of loop){}

3rd Sep 2019, 8:54 PM
SCP 251
SCP 251 - avatar
2 Answers
+ 2
Create a class that controls how each instance is drawn to the canvas. Check this code to see how. You use the loop and push new instances into an array. https://code.sololearn.com/Wi3p3Ham9qJ5/?ref=app
3rd Sep 2019, 9:31 PM
Zeke Williams
Zeke Williams - avatar
+ 1
Hi, you can define a class for add a style to a single canvas element and make a loop to create all of them. Run this code as example: <!DOCTYPE html> <html> <body> <style> .canvas-example{ border: 1px solid red; } </style> <script> var c = document.createElement('canvas'); var target = document.body; for(var i=0; i < 10; i++){ c = document.createElement('canvas'); c.setAttribute('id', 'Canvas'+i); c.classList.add('canvas-example'); target.appendChild(c); } </script> <!-- RETURN HTML IS <canvas id="Canvas0" class="canvas-example"></canvas> <canvas id="Canvas1" class="canvas-example"></canvas> <canvas id="Canvas2" class="canvas-example"></canvas> <canvas id="Canvas3" class="canvas-example"></canvas> <canvas id="Canvas4" class="canvas-example"></canvas> <canvas id="Canvas5" class="canvas-example"></canvas> <canvas id="Canvas6" class="canvas-example"></canvas> <canvas id="Canvas7" class="canvas-example"></canvas> <canvas id="Canvas8" class="canvas-example"></canvas> <canvas id="Canvas9" class="canvas-example"></canvas> --> </body> </html>
3rd Sep 2019, 9:32 PM
Gabriele Marra
Gabriele Marra - avatar