Skip to content

Instantly share code, notes, and snippets.

@dipamsen
Created February 14, 2021 11:06
Show Gist options
  • Save dipamsen/c59e02991929db850373b3c7d1a858ef to your computer and use it in GitHub Desktop.
Save dipamsen/c59e02991929db850373b3c7d1a858ef to your computer and use it in GitHub Desktop.
const w = 400, h = 400
setupWindow(w, h)
// import required even though the variable "p5" will not be used anywhere
const p5 = require("p5")
// Declare sketch variables here
function setup() {
createCanvas(w, h);
// Setup function
// use saveAsPNG at end of setup if all animation is done in setup
}
function draw() {
background(0);
translate(width / 2, height / 2);
// ...
// Draw function
// ...
// use saveAsPNG at end of draw if all animation is done in the first frame of draw loop
// use saveAsPNG at end of draw with exit=false if each frame has to be saved as png (add exit condition with noLoop())
}
// p5Inst = instance of p5 (in global mode it is "global")
// filename = name of file
// exit = if true, will stop the node process from running after saving the file
async function saveAsPNG(p5Inst, filename = "sketch", exit = true) {
const fs = require("fs");
const buffer = p5Inst._renderer.drawingContext.canvas.toBuffer()
await fs.promises.writeFile(filename + ".png", buffer)
if (exit) process.exit(0)
}
// w = width of canvas
// h = height of canvas
function setupWindow(w = 100, h = 100) {
const { createCanvas } = require("canvas");
const { JSDOM } = require("jsdom")
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)
};
const { performance } = require("perf_hooks")
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" }
global.setup = setup
global.draw = draw
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment