Skip to content

Instantly share code, notes, and snippets.

@dipamsen
Created February 14, 2021 11:30
Show Gist options
  • Save dipamsen/3e898a0acf73f6b58a563981732b4fdc to your computer and use it in GitHub Desktop.
Save dipamsen/3e898a0acf73f6b58a563981732b4fdc to your computer and use it in GitHub Desktop.
const w = 400, h = 400
setupWindow(w, h)
const p5 = require("p5")
new p5(p => {
// Declare sketch variables here
p.setup = () => {
p.createCanvas(w, h)
// setup function
saveAsPNG(p, "name") // will not run draw
}
// p.draw = () => {
// // draw function
// }
})
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)
}
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" }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment