HTML5 CANVAS Sandbox

Create grid of evenly spaced points and then add some randomness +/- r/2

by JeffC

HTML

<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes -->

<body onload="draw();">
  <canvas id="canvas"></canvas>
</body>

JavaScript

//arc(x, y, radius, startAngle (radians), endAngle (radians), anticlockwise);

function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var height = 500;
    var width = 500;
    var r = 5;
    canvas.height = height;
    canvas.width = width;
    ctx.save();

    createBorder(ctx, width, height);

    // draw stuff
    ctx.strokeStyle = "#F00";
    ctx.lineWidth = 1;
    for (var x = r; x <= width - r; x += r + r) {
      for (var y = r; y <= height - r; y += r + r) {
        ctx.beginPath();
        var offsetX = getRandomIntInclusive(-r / 2, r / 2);
        var offsetY = getRandomIntInclusive(-r / 2, r / 2);
        drawCircle(ctx, x + offsetX, y + offsetY, 1);
        // drawPointRect(ctx, x + offsetX, y + offsetY);
        ctx.closePath();
        ctx.stroke();
      }
    }
  }
}

function drawCircle(ctx, x, y, r) {
  ctx.arc(x, y, r, 0, Math.PI * 2, true);
}

function drawPointLine(ctx, x, y) {
  ctx.moveTo(x, y);
  ctx.lineTo(x + 1, y);
}

function drawPointRect(ctx, x, y) {
  ctx.fillRect(x, y, 1, 1);
}

// Returns a random integer between min (included) and max (included)
// Using Math.round() will give you a non-uniform distribution!
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function createBorder(ctx, width, height) {
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(0, height);
  ctx.lineTo(width, height);
  ctx.lineTo(width, 0);
  ctx.lineTo(0, 0);
  ctx.lineWidth = 3;
  ctx.stroke();
  ctx.restore();
}