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.
Following canvas shows a rudimentary color palette.
Another example of color change propagation:
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
Example 0.2: A Random-Number Distribution
Example 0.3: A Walker That Tends to Move to the Right
Example 0.4 A Gaussian Distribution
Example 0.4 An Accept-Reject Distribution
Figure 0.4 A Graph of Perlin noise values over time (left) and random noise values over time (right)
Example 0.6 A Perlin Noise Walker
Figure 0.9: Each pixel represents a noise value as a grayscale color
3. Vectors
Example 1.1: Bouncing Ball with No Vectors
Example 1.2: Bouncing Ball with Vectors
Example 1.3: Vector Subtraction (Hover cursor over canvas to see result)
Example 1.4: Multiplying a Vector (Hover cursor over canvas to see result)
Example 1.5: Vector Magnitude (Hover cursor over canvas to see result)
Example 1.6: Normalizing a Vector (Hover cursor over canvas to see result)
Example 1.7: Motion 101 (Velocity)
Example 1.8: Motion 101 (Velocity and Constant Acceleration)
Example 1.9: Motion 101 (Velocity and Random Acceleration)
Example 1.10: Accelerating Toward the Mouse
4. Revision History
- 2025-04-08 (Tue): Introduce chapter Randomness and Vectors
Footnotes:
Nature of Code, by Daniel Shiffman: https://natureofcode.com
HTML specific export settings: https://emacsdocs.org/docs/org/HTML-specific-export-settings
Quoting HTML tags: https://emacsdocs.org/docs/org/Quoting-HTML-tags
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,