JSFiddle - React, Tailwind, and code Playground

by brantolsen

HTML

<div>
Count: <input id="count" type="text" value="0"></input>
</div>
<div>
<canvas width="500px" id="myCanvas"></canvas>
</div>

JavaScript

function doit(count) {
    var x, y;
    x = 0;
    y = 200;
    
    for (var index = 0; index < count; ++index)
    {
      drawRectangle(x, y, 200, 100);
        
      // Update the coordinates for the next rectangle.
      y = y + 110;
      x = x + 50;
    }
}

function drawRectangle(left, top, width, height) {
    if (document.createElement) {
        newdiv = document.createElement("div");
        newdiv.style.position = "absolute";
        newdiv.style.left = left + "px";
        newdiv.style.top = top + "px";
        newdiv.style.width = width + "px";
        newdiv.style.height = height + "px";
        newdiv.style.backgroundColor = 'red';
        newdiv.style.visibility = 'visible';
        newdiv.id = 'newdiv';
        document.body.appendChild(newdiv);

        // Must update after the div is appended.
        newdiv.innerHTML = "X: " + newdiv.offsetLeft + "<br>Y: " + newdiv.offsetTop + "<br>Width: " + newdiv.clientWidth + "<br>Height: " + newdiv.clientHeight;
    }
}

function drawOnCanvas(count) {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgb(200,0,0)";

    var listOfRects, x, y;
    listOfRects = [];
    x = 0;
    y = 0;
    for (var index = 0; index < count; ++index)
    {  
      listOfRects.push({
          x: x,
          y: y,
          w: 10,
          h: 15
      });
      // Update the coordinates for the next rectangle.
      x = x + 15;
      y = y + 2;
    }

    // Clear existing rectangles.    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // Draw all the new rectangles.
    for (var index = 0; index < listOfRects.length; ++index) {
        var rect = listOfRects[index];
        ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
    }
}

// Draw 1 rectangle on both the canvas and the divs.
drawOnCanvas(1);
doit(1);

// Add handler to determine when the count has changed.
var input = document.getElementById("count");
input.onchange = function() {
   ...