How to Join multiple rectangles using html5 and CSS?

Joined
Sep 4, 2022
Messages
134
Reaction score
16
Hello !

canvas are design to draw,
in the code from stackoverflow, all rectangles are made within a loop.

like 15 is mention, it's 16 rectangles draw in the canvas area.

the basic 'pattern' is all inside a 'table' tag.
the JS function set a rectangle at each loop
and create a new one
until 16 rectangle are in the canvas
 
Last edited:
Joined
Jul 4, 2023
Messages
487
Reaction score
61
The provided code is a combination of HTML and JavaScript that creates a table with rows, each containing a canvas element. This canvas element is then filled with a gray color using JavaScript.

this code generates a table with 15 rows, each containing a canvas element, the canvas elements are uniquely identified using IDs
HTML:
@for(var i=1;i<=15;i++)
{
  <tr>
  <td style="width:20px;"></td>
  <td>                               
  <canvas id="newCanvas_@i" width="200" height="8" style="border:1px solid #000000;"></canvas>                                             
  </td>
  </tr>
}

and the JavaScript code applies the gray color to each canvas
JavaScript:
for(var i=1;i<=15;i++)
{
  var c = document.getElementById('newCanvas'+"_"+i)
  var ctx = c.getContext('2d');
  ctx.fillStyle = '#708090';
  ctx.fillRect(0, 0, 200, 10);
}

The result is a series of gray bars within the canvas elements, arranged in a table format.


But there is also another way to do it. You can do both "actions" in the same javascript loop e.g.
HTML:
<div class="panel"></div>

<style>
  .panel {
    display: flex;
    flex-direction: column;
    width: 200px;
  }
  .panel canvas {
    border: 1px solid #000000;
  }
</style>

<script>
  const panel = document.querySelector('.panel'),
        rows = document.createDocumentFragment();

  for (let i=1; i<=15; i++) {
    const c = document.createElement('CANVAS');
    c.width = 200;
    c.height = 10;
    const ctx = c.getContext('2d');
    ctx.fillStyle = '#708090';
    ctx.fillRect(0, 0, c.width, c.height);
    rows.appendChild(c);
  }

  panel.appendChild(rows);
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top