final_version

by burki

HTML

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Canvas experiment</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="doit();">
    <canvas id="canvas"></canvas>
  </body>
  <script src="draw.js"></script>
</html>

JavaScript

const DEBUG = false; // true only makes sense for max <= 50 (the smaller the better)

function doit() {
  const canvas = document.getElementById("canvas");
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgb(0, 0, 0)";

  // fill canvas of size n times n
  const n = 500;
  canvas.setAttribute("width", n);
  canvas.setAttribute("height", n);
  let max = n * n; // ...with max = n * n pixels

  // for "real" randomness use:
  // const allValues = [...Array(max).keys()];
  // shuffleInPlace(allValues);

  // the same can be achieved with:
  // const nrr = new NonRepeatingRandom(max, true, max);

  const nrr = new NonRepeatingRandom(max); // start with defaults, i.e., maximize = true, maxPageSizes = [2]
  // some more examples, try them out!
  // const nrr = new NonRepeatingRandom(max, true, 5, 3, 2);
  // const nrr = new NonRepeatingRandom(max, false, 11);
  // const nrr = new NonRepeatingRandom(max, true, 11);
  // const nrr = new NonRepeatingRandom(max, true, 2, 3, 5);

  // get all values at once (of course, the entries can also be fetched individually)
  const allValues = nrr.next(max);

  function plotPixel() {
    let i = 100;
    // loop 100 times as long max >= 0
    while (--i >= 0 && --max >= 0) {
      const val = allValues[max];
      // comment out the previous line and uncomment the following
      // if you want to get the values one by one
      // const val = nrr.next(1)[0];
      const x = Math.trunc(val / n);
      const y = val % n;
      ctx.fillRect(x, y, 1, 1);
    }
    if (max > 0) {
      window.requestAnimationFrame(plotPixel);
    } else {
      console.info("FINISHED!");
    }
  }
  plotPixel();
}

/**
 * Shuffle array in place (Fisher/Yates/Durstenfeld/Knuth)
 *
 * @param {[*]} a
 */
function shuffleInPlace(a) {
  var j, x, i;
  for (i = a.length; i > 1; ) {
    j = Math.trunc(Math.random() * i); // or Math.floor
    x = a[--i];
    a[i] = a[j];
    a[j] = x;
  }
}

function assert(condition, message) {
  if (!condition) {
   ...