JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<h3>Grid with slightly offset intersections</h3>

<canvas id="canvas" width=350 height=350></canvas>

CSS

body {
    background-color: ivory;
}
#canvas {
    border:1px solid red;
}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// declare an array
var points = new Array(17);
for (var i = 0; i < points.length; i++) {
    points[i] = new Array(17);
}

var sideLength = 20;

// fill the array with 
for (var y = 0; y < 17; y++) {
    for (var x = 0; x < 17; x++) {
        // create a random semi-offset grid point
        var radius = 2.5 * Math.random();
        var radianAngle = 2 * Math.PI * Math.random();
        var cx = x * sideLength + radius * Math.cos(radianAngle);
        var cy = y * sideLength + radius * Math.sin(radianAngle);
        // if this is a sidepoint, don't offset (sides are straight)
        if (x == 0) {
            cx = 0;
        }
        if (y == 0) {
            cy = 0;
        }
        if (x == 16) {
            cx = x * sideLength;
        }
        if (y == 16) {
            cy = y * sideLength;
        }
        // add this gridpoint to the points array
        points[x][y] = {
            x: cx + 10,
            y: cy + 10
        };
    }
}

// stroke the 4 sides of each cell
for (var y = 0; y < 16; y++) {
    for (var x = 0; x < 16; x++) {
        strokeCell(x, y);
    }
}

// draw the 4 sides of the cell
function strokeCell(x, y) {
    var pt0 = points[x][y];
    var pt1 = points[x + 1][y];
    var pt2 = points[x + 1][y + 1];
    var pt3 = points[x][y + 1];

    ctx.beginPath();
    ctx.moveTo(pt0.x, pt0.y);
    ctx.lineTo(pt1.x, pt1.y);
    ctx.lineTo(pt2.x, pt2.y);
    ctx.lineTo(pt3.x, pt3.y);
    ctx.closePath();
    ctx.stroke();
}