Skip to content

Instantly share code, notes, and snippets.

@dipamsen
Last active February 15, 2021 13:45
Show Gist options
  • Save dipamsen/366783d2c1683a62ac2d46f83f2fe8b0 to your computer and use it in GitHub Desktop.
Save dipamsen/366783d2c1683a62ac2d46f83f2fe8b0 to your computer and use it in GitHub Desktop.
This is a simple program that generates a random walk visualization for laser etching on train whistles. Ported from CodingTrain/Random-Whistle

How to test directly:

  1. download these files
  2. npm install p5 canvas jsdom
  3. node sketch.js <any-random-seed-here>
  4. randomwalk will be saved as walk.png
const fs = require("fs");
async function saveAsPNG(p5Inst, filename = "sketch") {
const buffer = p5Inst._renderer.drawingContext.canvas.toBuffer()
await fs.promises.writeFile(filename + ".png", buffer)
}
function getBuffer(p5Inst) {
return p5Inst._renderer.drawingContext.canvas.toBuffer()
}
const { createCanvas } = require("canvas");
const { JSDOM } = require("jsdom")
const { performance } = require("perf_hooks")
function setupWindow(w, h) {
global.window = global
const dom = new JSDOM()
global.document = dom.window.document
const nodeCanvas = createCanvas(w, h)
dom.window.HTMLCanvasElement.prototype.getContext = (type) => {
return nodeCanvas.getContext(type)
};
global.performance = performance
global.screen = {}
global.addEventListener = dom.window.addEventListener.bind(dom.window)
global.removeEventListener = dom.window.removeEventListener.bind(dom.window)
global.navigator = { userAgent: "node" }
}
module.exports = { saveAsPNG, getBuffer, setupWindow }
const w = 4880, h = 1500;
const { saveAsPNG, setupWindow } = require("./functions");
setupWindow(w, h)
global.setup = setup;
const p5 = require("p5");
let x;
let y;
// let whistle;
let number = process.argv[2] || 123456;
function setup() {
createCanvas(w, h);
// whistle = createGraphics(4880, 1500);
pixelDensity(1);
background(255);
x = width / 2;
y = height / 2;
const stepSize = 4;
randomSeed(number);
for (let i = 0; i < 1000000; i++) {
//canvas.stroke(0);
//canvas.point(x, y);
noStroke();
fill(0);
rectMode(CENTER);
rect(x, y, stepSize, stepSize);
strokeWeight(stepSize);
const r = int(random(4));
switch (r) {
case 0:
x = x + stepSize;
break;
case 1:
x = x - stepSize;
break;
case 2:
y = y + stepSize;
break;
case 3:
y = y - stepSize;
break;
}
}
saveAsPNG(global, "walk");
remove();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment