The Nature of Code

Table of Contents

2025-04-08, Tue

I first came into "The Nature of Code" book1 authored by Daniel Shiffman several years ago in a second-hand bookstore and was instantly hooked by its design and topic. Now that the whole book is available online, I figured it's a good time to play code snippets in the book with vanilla JavaScript. This post intends to record the progress of the playthrough as well as hiccups that have been encountered.

1. Preparation

The Org-Mode export settings2, 3 like #+HTML: and #+BEGIN_EXPORT HTML are used in this post to wire JavaScript into the exported HTML page. To warm up, let's set up some canvases4 to see whether things work. Click the draw button below to see the first paint result: a welcome message, along with several color blocks.

Sample Canvas Element

Following canvas shows a rudimentary color palette.

Color Palette

Another example of color change propagation:

Color Palette

With things set up properly, it's time to go through examples and figures in the book.

2. Randomness

Example 0.1: A Tranditional Random Walker

A Traditional Random Walk

Example 0.2: A Random-Number Distribution

A Random-Number Distribution

Example 0.3: A Walker That Tends to Move to the Right

A Walker That Tends to Move Right

Example 0.4 A Gaussian Distribution

Gaussian Distribution

Example 0.4 An Accept-Reject Distribution

Accept-Reject Distribution

Figure 0.4 A Graph of Perlin noise values over time (left) and random noise values over time (right)

Noise over Time

Example 0.6 A Perlin Noise Walker

A Perlin Noise Walker

Figure 0.9: Each pixel represents a noise value as a grayscale color

2D Noise

3. Vectors

Example 1.1: Bouncing Ball with No Vectors

Bouncing Ball

Example 1.2: Bouncing Ball with Vectors

Bouncing Ball with Vectors

Example 1.3: Vector Subtraction (Hover cursor over canvas to see result)

Vector Subtraction

Example 1.4: Multiplying a Vector (Hover cursor over canvas to see result)

Vector Subtraction

Example 1.5: Vector Magnitude (Hover cursor over canvas to see result)

Vector Subtraction

Example 1.6: Normalizing a Vector (Hover cursor over canvas to see result)

Vector Subtraction

Example 1.7: Motion 101 (Velocity)

Vector Subtraction

Example 1.8: Motion 101 (Velocity and Constant Acceleration)

Vector Subtraction

Example 1.9: Motion 101 (Velocity and Random Acceleration)

Vector Subtraction

Example 1.10: Accelerating Toward the Mouse

Vector Subtraction

4. Revision History

Footnotes:

1

Nature of Code, by Daniel Shiffman: https://natureofcode.com

4

Some examples are provided by MDN as tutorials, e.g. Basic Usage of Canvas https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage,