outwest.dev

VueRAFCanvasExperiment

Experiment: Canvas Random Walk

· 3 min read

Lately, I've been on a bit of a late-night creative spree, tinkering with some fun experiments. These past few nights, I've been absorbed in crafting a nifty little random walk demo using Canvas and its handy 2D API.

The aim was to draw a random walk on a canvas. I first built the concept with p5.js, which got me a working proof of concept in about an hour. After that, I moved it to the native Canvas API.



Setting Up the Pixels

Instead of drawing shapes, we write pixels directly. We start by creating a blank ImageData object the same size as our canvas. The nice part here is all of the pixels in the new object start out transparent.

const imgData = ctx.createImageData(width, height);

It's important to remember that an ImageData object's data property is a Uint8ClampedArray. It's one flat array, with four values per pixel in RGBA order, each from 0 to 255.

So to set a single pixel, we need to find where it starts in that array:

const draw = (imgData, _x, _y) => {
  let x = _x % width;
  let y = _y % height;

  if (x < 0) {
    x += width;
  }

  if (y < 0) {
    y += height;
  }

  // 8-bit integer array representing the data in the RGBA order
  const pixelIndex = (y * width + x) * 4;

  // Sets a single pixel in the image data
  imgData.data[pixelIndex] = 255;
  imgData.data[pixelIndex + 1] = 255;
  imgData.data[pixelIndex + 2] = 255;
  imgData.data[pixelIndex + 3] = 255;
}

It took me a minute to wrap my head around pixelIndex, but we're converting 2D coordinates into a position in a 1D array. Multiplying y by the width gives us the starting index of the row. Then we add x to find the exact pixel within that row. We then multiply by 4 because each pixel takes up four values (RGBA).

The % at the top wraps the walk around the edges: if it wanders off the right side, it comes back on the left, and the same for top and bottom.

Taking a Step

Each step moves a small random amount from the last position:

const genPixels = () => {
  const x = lastX + (Math.random() - 0.5) * 8;
  const y = lastY + (Math.random() - 0.5) * 8;

  const nx = Math.round(cx + x);
  const ny = Math.round(cy - y);

  draw(imgData, nx, ny);

  lastX = x;
  lastY = y;
}

Math.random() - 0.5 gives a value between -0.5 and 0.5, so each step moves up to 4 pixels in any direction. The position is stored relative to the center of the canvas (cx, cy), so the walk starts in the middle.

The Loop

Next we use requestAnimationFrame (through VueUse's useRafFn) to run our loop once per frame:

const PIXELS_PER_FRAME = 10;

const loop = () => {
  for (let i = 0; i < PIXELS_PER_FRAME; i++) genPixels();
  ctx.putImageData(imgData, 0, 0);
}

Each frame takes 10 steps, one after another, then copies the updated pixels to the canvas once. Copying once per frame instead of once per step keeps it cheap. Changing PIXELS_PER_FRAME, or making it a ref, controls how fast the walk draws, independent of the frame rate.

Conclusion

This project took me far from my usual tasks, but it was a fun adventure that pushed me beyond my comfort zone for a couple of nights. I later used a random walk like this one to stir the ink in Stable fluids in 150 lines.