Nature of Code: Walker

29 September 2024 | Eric

Introduction

Recently, I purchased Daniel Shiffman book The Nature of Code and wanted to share my experimentation here. You might already know Daniel for his YouTube channel named The Coding Train.

If you want to give it a try, you can just read it online, no need to purchase the paper version.

Daniel uses p5.js for everything, but I must say it was quite a challenge to set it up in Astro. It feels like p5.js is first and foremost an educational platform that is not necessarily meant to be integrated in a web environment. For example, their npm package is not minified and weight 1.48M on this page (sorry, will try to fix that later…).

Their documentation is also very much focused on using the web editor, which is awesome because you don’t need to install anything but obviously when you want to do some custom integration then it’s getting a bit difficult. They have a VSCode extension, great! But I don’t use VSCode… anyway, after a bit of tinkering, it’s finally working!

Daniel has a video about P5.js instance mode which helped me quite a bit to avoid having everything in the global scope.

The walker example in P5.js:

Walker

Code

Now that I have this setup, I can also show some code, which is also pretty neat. Below is the render function of my Walker class:


/**
 * Renders circles on the canvas by iterating through the list of circles
 * and drawing each one with a specific alpha value based on the frame count.
 *
 * @param {number} currentFrameCount - The current frame count used to determine the alpha value of the circles.
 * @return {void} - This method does not return any value.
 */
renderCircles(currentFrameCount: number) {
  for (const circle of this.circles) {
    const alpha = this.alphaIncrement * (this.n - (currentFrameCount - circle.frameCount));
    this.p.stroke(this.p.color(`hsla(${circle.frameCount % 360}, 100%, 50%, ${alpha})`));
    this.p.circle(circle.x, circle.y, this.radius * 2);
  }
}

Anyway, that was just a fun little example. I’ll go back to reading the book now.

Cheers! 👋