And finally the “3D Knot” p5js version. Watch it online below:
OpenProcessing.org/sketch/608726
However, there’s a worse bug in it: the last stroke() determines the color for all vertex()!
“index.html”:
<!DOCTYPE html>
<meta charset=utf-8>
<meta name=viewport content=width=device-width,initial-scale=1>
<script async src=https://cdn.JsDelivr.net/npm/p5/lib/p5.js></script>
<script defer src=sketch.js></script>
“sketch.js”:
/**
* 3D Knot (2017/Dec)
* Daniel Shiffman
* https://YouTu.be/r6YMKr1X0VA
*
* Mod GoToLoop (v1.0.1) (2018/Oct/16)
* https://OpenProcessing.org/sketch/608725 (pjs)
* https://OpenProcessing.org/sketch/608726 (p5js)
*
* https://Discourse.Processing.org/t/
* vertex-loop-and-draw-along-a-vertex-path/4545/5
*/
/**
* http://PaulBourke.net/geometry/knots/
* Knot 4 (1992/Oct):
*
* r(beta) = 0.8 + 1.6 * sin(6 * beta)
* theta(beta) = 2 * beta
* phi(beta) = 0.6 * pi * sin(12 * beta)
*
* x = r * cos(phi) * cos(theta)
* y = r * cos(phi) * sin(theta)
* z = r * sin(phi)
*/
"use strict";
const π = Math.PI, ANGLE_STEP = .02, BETA_STEP = .01,
MAG = 100.0, SEGS_LIMIT = π + BETA_STEP,
PI_DOT_6 = π*.6,
knots = []
let α = 0.0, β = 0.0, paused = false, bg
function setup() {
createCanvas(600, 600, WEBGL).mousePressed(togglePause)
bg = color(0)
colorMode(HSB).strokeWeight(8.0).noFill()
}
function draw() {
background(bg).rotateY(α += ANGLE_STEP)
β <= SEGS_LIMIT && addKnot()
β += BETA_STEP
beginShape()
for (const { c, v } of knots) stroke(c).vertex(v.x, v.y, v.z)
endShape()
}
function togglePause() {
(paused = !paused)? noLoop() : loop()
}
function keyPressed() {
togglePause()
}
function addKnot() {
const r = MAG * (.8 + sin(6*β)*1.6),
θ = 2*β, φ = PI_DOT_6 * sin(12*β),
rCosφ = r * cos(φ),
x = rCosφ * cos(θ), y = rCosφ * sin(θ), z = r * sin(φ),
knot = new Knot(x, y, z)
knots.push(knot)
console.log(knots.length + ':', knot)
}
class Knot {
constructor(...vec) {
this.v = vec.length === 1? vec[0] : createVector(...vec)
this.c = color(this.v.mag(), 100, 100)
}
}