From 562730dd07e6a53ed958f11321ec5f6f609d0d8f Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 18:42:28 -0500 Subject: [PATCH 01/13] Add platform specific build --- package.json | 6 ++++++ rolldown.config.js | 13 +++++++++++++ src/app.js | 3 ++- src/core/init.js | 16 ---------------- src/core/platform/browser.js | 21 +++++++++++++++++++++ src/core/platform/node.js | 6 ++++++ 6 files changed, 48 insertions(+), 17 deletions(-) create mode 100644 src/core/platform/browser.js create mode 100644 src/core/platform/node.js diff --git a/package.json b/package.json index cab34320e0..b4613315b9 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,12 @@ }, "license": "LGPL-2.1", "browser": "./lib/p5.min.js", + "imports": { + "#platform": { + "p5-node": "./src/core/platform/node.js", + "default": "./src/core/platform/browser.js" + } + }, "exports": { ".": { "types": "./types/p5.d.ts", diff --git a/rolldown.config.js b/rolldown.config.js index c1403cce6f..e02a6b1795 100644 --- a/rolldown.config.js +++ b/rolldown.config.js @@ -81,6 +81,19 @@ export default defineConfig([ // }) ] }, + //// Node build //// + { + input: 'src/app.js', + output: { + file: './lib/p5.node.esm.js', + format: 'esm', + banner + }, + resolve: { + conditionNames: ['p5-node', 'import', 'default'] + }, + plugins + }, //// Addon module builds (e.g. WebGPU) //// ...['webgpu'].map(module => ({ input: `src/${module}/index.js`, diff --git a/src/app.js b/src/app.js index bacb900420..a3b8896738 100644 --- a/src/app.js +++ b/src/app.js @@ -64,7 +64,8 @@ p5.registerAddon(strands); import svg from './shape/svg/p5.svg'; p5.registerAddon(svg); -import { waitForDocumentReady, _globalInit } from './core/init'; +import { _globalInit } from './core/init'; +import { waitForDocumentReady } from '#platform'; waitForDocumentReady().then(_globalInit); export default p5; diff --git a/src/core/init.js b/src/core/init.js index 72020beb8e..1b1d5ab989 100644 --- a/src/core/init.js +++ b/src/core/init.js @@ -35,19 +35,3 @@ export const _globalInit = () => { } } }; - -// make a promise that resolves when the document is ready -export const waitForDocumentReady = () => { - if (typeof document !== 'undefined') { - return new Promise((resolve, reject) => { - // if the page is ready, initialize p5 immediately - if (document.readyState === 'complete') { - resolve(); - // if the page is still loading, add an event listener - // and initialize p5 as soon as it finishes loading - } else { - window.addEventListener('load', resolve, false); - } - }); - } -}; diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js new file mode 100644 index 0000000000..9b5c665ab9 --- /dev/null +++ b/src/core/platform/browser.js @@ -0,0 +1,21 @@ +/** + * Browser adapter. Everything p5 needs from its host environment should go + * through this module, so that non-browser builds can swap in + * alternate implementations instead. + */ + +// make a promise that resolves when the document is ready +export const waitForDocumentReady = () => { + if (typeof document !== 'undefined') { + return new Promise((resolve, reject) => { + // if the page is ready, initialize p5 immediately + if (document.readyState === 'complete') { + resolve(); + // if the page is still loading, add an event listener + // and initialize p5 as soon as it finishes loading + } else { + window.addEventListener('load', resolve, false); + } + }); + } +}; diff --git a/src/core/platform/node.js b/src/core/platform/node.js new file mode 100644 index 0000000000..d0e9cab6b7 --- /dev/null +++ b/src/core/platform/node.js @@ -0,0 +1,6 @@ +/** + * Node adapter, used in place of `platform.js` by the p5.node build. + */ + +// There is no document to wait for +export const waitForDocumentReady = () => Promise.resolve(); From e95c830adac22e0c190c5f303ce40ae3993894f1 Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 18:44:31 -0500 Subject: [PATCH 02/13] Try globalThis instead of window --- src/friendly_errors/fes_core.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/friendly_errors/fes_core.js b/src/friendly_errors/fes_core.js index ef6b94770d..ad695e224a 100644 --- a/src/friendly_errors/fes_core.js +++ b/src/friendly_errors/fes_core.js @@ -181,7 +181,7 @@ function fesCore(p5, fn, lifecycles) { // if using instance mode, this function would be called with the current // instance as context const instanceMode = context instanceof p5; - context = instanceMode ? context : window; + context = instanceMode ? context : globalThis; const fnNames = entryPoints; if (context.preload && !p5.isPreloadSupported()) { From 4f6625e0f4f5fdbc7b1b2315f3974eb0c0bfbcb7 Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:00:51 -0500 Subject: [PATCH 03/13] Factor out uncaught error handling --- src/core/platform/browser.js | 15 +++++++++++++++ src/core/platform/node.js | 8 ++++++++ src/friendly_errors/fes_core.js | 15 +++------------ 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js index 9b5c665ab9..b5b5db69fb 100644 --- a/src/core/platform/browser.js +++ b/src/core/platform/browser.js @@ -19,3 +19,18 @@ export const waitForDocumentReady = () => { }); } }; + +export const handleUncaughtErrors = callback => { + const handler = e => { + let error; + if (e instanceof ErrorEvent) { + error = e.error; + } else if (e instanceof PromiseRejectionEvent) { + error = e.reason; + if (!(error instanceof Error)) return; + } + if (error) callback(error); + }; + window.addEventListener('error', handler, false); + window.addEventListener('unhandledrejection', handler, false); +}; diff --git a/src/core/platform/node.js b/src/core/platform/node.js index d0e9cab6b7..c5d9f9f980 100644 --- a/src/core/platform/node.js +++ b/src/core/platform/node.js @@ -4,3 +4,11 @@ // There is no document to wait for export const waitForDocumentReady = () => Promise.resolve(); + +export const handleUncaughtErrors = callback => { + // Node rethrows unhandled promise rejections as uncaught exceptions, so they + // are caught here too + process.on('uncaughtExceptionMonitor', error => { + if (error instanceof Error) callback(error); + }); +}; diff --git a/src/friendly_errors/fes_core.js b/src/friendly_errors/fes_core.js index ad695e224a..bbcc620922 100644 --- a/src/friendly_errors/fes_core.js +++ b/src/friendly_errors/fes_core.js @@ -30,6 +30,7 @@ import { getFriendlyStack } from './stacktrace'; import { FES } from './fes'; +import { handleUncaughtErrors } from '#platform'; function fesCore(p5, fn, lifecycles) { // This is a lazily-defined list of p5 symbols that may be @@ -372,16 +373,7 @@ function fesCore(p5, fn, lifecycles) { defineMisusedAtTopLevelCode(); } - // Try to get the error object from e - let error; - if (e instanceof Error) { - error = e; - } else if (e instanceof ErrorEvent) { - error = e.error; - } else if (e instanceof PromiseRejectionEvent) { - error = e.reason; - if (!(error instanceof Error)) return; - } + const error = e; if (!error) return; let stacktrace = errorStackParser.parse(error); @@ -595,8 +587,7 @@ function fesCore(p5, fn, lifecycles) { lifecycles.presetup = function () { checkForUserDefinedFunctions(); - window.addEventListener('error', fesErrorMonitor, false); - window.addEventListener('unhandledrejection', fesErrorMonitor, false); + handleUncaughtErrors(fesErrorMonitor); }; } From 6acba6cd0ac61d641646c5d3cca4e67100e51f3c Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:03:30 -0500 Subject: [PATCH 04/13] Factor out script reading from FES --- src/core/platform/browser.js | 7 +++++++ src/core/platform/node.js | 3 +++ src/friendly_errors/sketch_verifier.js | 7 +++---- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js index b5b5db69fb..8430e3b64a 100644 --- a/src/core/platform/browser.js +++ b/src/core/platform/browser.js @@ -34,3 +34,10 @@ export const handleUncaughtErrors = callback => { window.addEventListener('error', handler, false); window.addEventListener('unhandledrejection', handler, false); }; + +export const getUserScript = () => { + // TODO: think of a more robust way to get the user's code. Refer to + // https://github.com/processing/p5.js/pull/7293. + const scripts = document.querySelectorAll('script'); + return scripts[scripts.length - 1]; +}; diff --git a/src/core/platform/node.js b/src/core/platform/node.js index c5d9f9f980..14293252e5 100644 --- a/src/core/platform/node.js +++ b/src/core/platform/node.js @@ -12,3 +12,6 @@ export const handleUncaughtErrors = callback => { if (error instanceof Error) callback(error); }); }; + +// TODO: maybe read process.argv[1]? +export const getUserScript = () => undefined; diff --git a/src/friendly_errors/sketch_verifier.js b/src/friendly_errors/sketch_verifier.js index 45a40608cd..c5c86d4804 100644 --- a/src/friendly_errors/sketch_verifier.js +++ b/src/friendly_errors/sketch_verifier.js @@ -2,6 +2,7 @@ import { parse } from 'acorn'; import { simple as walk } from 'acorn-walk'; import * as constants from '../core/constants'; import { FES } from './fes'; +import { getUserScript } from '#platform'; // List of functions to ignore as they either are meant to be re-defined or // generate false positive outputs. @@ -207,10 +208,8 @@ export const verifierUtils = { * @returns {Promise} The user's code as a string. */ getUserCode: async function () { - // TODO: think of a more robust way to get the user's code. Refer to - // https://github.com/processing/p5.js/pull/7293. - const scripts = document.querySelectorAll('script'); - const userCodeScript = scripts[scripts.length - 1]; + const userCodeScript = getUserScript(); + if (!userCodeScript) return ''; const userCode = await verifierUtils.fetchScript(userCodeScript); return userCode; From 2ff53282004f4b43d4b3d10143ccb35cdecdaf3d Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:06:04 -0500 Subject: [PATCH 05/13] Move acceleration code under a window check --- src/events/acceleration.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/events/acceleration.js b/src/events/acceleration.js index 62ab0dbaa1..5b733cff91 100644 --- a/src/events/acceleration.js +++ b/src/events/acceleration.js @@ -9,11 +9,15 @@ function acceleration(p5, fn, lifecycles) { lifecycles.presetup = function () { const events = ['deviceorientation', 'devicemotion']; - for (const event of events) { - window.addEventListener(event, this[`_on${event}`].bind(this), { - passive: false, - signal: this._removeSignal - }); + // TODO: maybe move to platform-dependent if there's a way to do this in + // node + if (typeof window !== 'undefined') { + for (const event of events) { + window.addEventListener(event, this[`_on${event}`].bind(this), { + passive: false, + signal: this._removeSignal + }); + } } // Initialize device orientation value From e2669c281aa13669fa8134dd32086ee2e81bda21 Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:08:56 -0500 Subject: [PATCH 06/13] Put more stuff behind window checks --- src/events/keyboard.js | 14 +++++++++----- src/events/pointer.js | 30 +++++++++++++++++------------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/src/events/keyboard.js b/src/events/keyboard.js index 11cc05f394..ea795dbe1f 100644 --- a/src/events/keyboard.js +++ b/src/events/keyboard.js @@ -18,11 +18,15 @@ function keyboard(p5, fn, lifecycles) { lifecycles.presetup = function () { const events = ['keydown', 'keyup', 'keypress', 'blur']; - for (const event of events) { - window.addEventListener(event, this[`_on${event}`].bind(this), { - passive: false, - signal: this._removeSignal - }); + // TODO: maybe move to platform-dependent once there is a way to receive + // keyboard events in node + if (typeof window !== 'undefined') { + for (const event of events) { + window.addEventListener(event, this[`_on${event}`].bind(this), { + passive: false, + signal: this._removeSignal + }); + } } }; diff --git a/src/events/pointer.js b/src/events/pointer.js index 3bd1b1c975..10d23620c6 100644 --- a/src/events/pointer.js +++ b/src/events/pointer.js @@ -17,20 +17,24 @@ function pointer(p5, fn, lifecycles) { 'dblclick', 'wheel' ]; - for (const event of events) { - window.addEventListener(event, this[`_on${event}`].bind(this), { - passive: false, - signal: this._removeSignal - }); - } + // TODO: maybe move to platform-dependent once there is a way to receive + // pointer events in node + if (typeof window !== 'undefined') { + for (const event of events) { + window.addEventListener(event, this[`_on${event}`].bind(this), { + passive: false, + signal: this._removeSignal + }); + } - window.addEventListener( - 'blur', - () => { - this.mouseIsPressed = false; - }, - { signal: this._removeSignal } - ); + window.addEventListener( + 'blur', + () => { + this.mouseIsPressed = false; + }, + { signal: this._removeSignal } + ); + } }; /** From 1b5a84f625ab9b6fc395350ce4ac43ee35a0d77f Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:10:05 -0500 Subject: [PATCH 07/13] looks like another case of s/window/globalThis/g --- src/friendly_errors/param_validator.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/friendly_errors/param_validator.js b/src/friendly_errors/param_validator.js index 8510831344..471e0e1487 100644 --- a/src/friendly_errors/param_validator.js +++ b/src/friendly_errors/param_validator.js @@ -215,8 +215,8 @@ function validateParams(p5, fn, lifecycles) { ); } // JavaScript classes, e.g. Request - else if (baseType.match(/^[A-Z]/) && baseType in window) { - typeSchema = z.instanceof(window[baseType]); + else if (baseType.match(/^[A-Z]/) && baseType in globalThis) { + typeSchema = z.instanceof(globalThis[baseType]); } // Generate a schema for a single parameter that can be of multiple // types / constants, i.e. `String|Number|Array`. From c0fda5fb71c913ff858e4c1571f3c585787111ef Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:13:21 -0500 Subject: [PATCH 08/13] oops we were referencing an assumed global p5 --- src/friendly_errors/fes_core.js | 2 +- src/friendly_errors/param_validator.js | 3 ++- src/friendly_errors/stacktrace.js | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/friendly_errors/fes_core.js b/src/friendly_errors/fes_core.js index bbcc620922..b136527c86 100644 --- a/src/friendly_errors/fes_core.js +++ b/src/friendly_errors/fes_core.js @@ -379,7 +379,7 @@ function fesCore(p5, fn, lifecycles) { let stacktrace = errorStackParser.parse(error); // process the stacktrace from the browser and simplify it to give // friendlyStack. - let [isInternal, friendlyStack] = processStack(error, stacktrace); + let [isInternal, friendlyStack] = processStack(error, stacktrace, p5); // if this is an internal library error, the type of the error is not relevant, // only the user code that lead to it is. diff --git a/src/friendly_errors/param_validator.js b/src/friendly_errors/param_validator.js index 471e0e1487..2705d78dc9 100644 --- a/src/friendly_errors/param_validator.js +++ b/src/friendly_errors/param_validator.js @@ -569,7 +569,8 @@ function validateParams(p5, fn, lifecycles) { } else { const [, stacktrace] = processStack( null, - errorStackParser.parse(Error()).slice(3) + errorStackParser.parse(Error()).slice(3), + p5 ); const locationStr = getFriendlyStack(stacktrace, true); FES.log`${locationStr} ${message}`(); diff --git a/src/friendly_errors/stacktrace.js b/src/friendly_errors/stacktrace.js index 015e429705..9a142fa237 100644 --- a/src/friendly_errors/stacktrace.js +++ b/src/friendly_errors/stacktrace.js @@ -261,13 +261,14 @@ export const errorStackParser = new ErrorStackParser(); * @private * @param {Error} error * @param {Array} stacktrace + * @param {Function} p5 the p5 class, which holds the FES log cache * * @returns {Array} An array with two elements, [isInternal, friendlyStack] * isInternal: a boolean value indicating whether the error * happened internally * friendlyStack: the filtered (simplified) stacktrace */ -export const processStack = (error, stacktrace) => { +export const processStack = (error, stacktrace, p5) => { // cannot process a stacktrace that doesn't exist if (!stacktrace) return [false, null]; From 48d856eb30257659ee967e82f4fd7865388c4051 Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:20:42 -0500 Subject: [PATCH 09/13] Duck type canvas checks --- src/core/platform/browser.js | 2 ++ src/core/platform/node.js | 3 +++ src/friendly_errors/param_validator.js | 5 ++++- 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js index 8430e3b64a..b5f6ad5fa5 100644 --- a/src/core/platform/browser.js +++ b/src/core/platform/browser.js @@ -41,3 +41,5 @@ export const getUserScript = () => { const scripts = document.querySelectorAll('script'); return scripts[scripts.length - 1]; }; + +export const isCanvasElement = data => data instanceof HTMLCanvasElement; diff --git a/src/core/platform/node.js b/src/core/platform/node.js index 14293252e5..0a70249f1b 100644 --- a/src/core/platform/node.js +++ b/src/core/platform/node.js @@ -15,3 +15,6 @@ export const handleUncaughtErrors = callback => { // TODO: maybe read process.argv[1]? export const getUserScript = () => undefined; + +// This prop is added in the wgpu code so we can identify it here +export const isCanvasElement = data => data?.isP5WGPUCanvas === true; diff --git a/src/friendly_errors/param_validator.js b/src/friendly_errors/param_validator.js index 2705d78dc9..7e5cd40d9b 100644 --- a/src/friendly_errors/param_validator.js +++ b/src/friendly_errors/param_validator.js @@ -6,6 +6,7 @@ import * as constants from '../core/constants.js'; import * as z from 'zod/mini'; import dataDoc from '../../docs/parameterData.json'; import { FES } from './fes.js'; +import { isCanvasElement } from '#platform'; import { errorStackParser, processStack, @@ -80,7 +81,6 @@ function validateParams(p5, fn, lifecycles) { const webAPIObjects = [ 'AudioNode', - 'HTMLCanvasElement', 'HTMLElement', 'KeyboardEvent', 'MouseEvent', @@ -100,6 +100,9 @@ function validateParams(p5, fn, lifecycles) { } const webAPISchemas = generateWebAPISchemas(webAPIObjects); + webAPISchemas.HTMLCanvasElement = z.custom(isCanvasElement, { + message: 'Expected a HTMLCanvasElement' + }); // Add web API schemas to the schema map. Object.assign(schemaMap, webAPISchemas); From 105355f2a36f1e15b97c929f3e70d0fb3eebc2f6 Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 19:34:58 -0500 Subject: [PATCH 10/13] Attempt to make some canvas setting apis --- src/core/p5.Renderer2D.js | 32 ++++++++------------------------ src/core/p5.Renderer3D.js | 27 +++++---------------------- src/core/platform/browser.js | 30 ++++++++++++++++++++++++++++++ src/core/platform/node.js | 14 ++++++++++++++ 4 files changed, 57 insertions(+), 46 deletions(-) diff --git a/src/core/p5.Renderer2D.js b/src/core/p5.Renderer2D.js index 44a8ad9aa0..ae45f18689 100644 --- a/src/core/p5.Renderer2D.js +++ b/src/core/p5.Renderer2D.js @@ -7,6 +7,7 @@ import { Element } from '../dom/p5.Element'; import { MediaElement } from '../dom/p5.MediaElement'; import { RGBP3 } from '../color/color_constants'; import FilterRenderer2D from '../image/filterRenderer2D'; +import { markP5Canvas, setCanvasSize, attachCanvas } from '#platform'; import { Matrix } from '../math/p5.Matrix'; import { PrimitiveToPath2DConverter } from '../shape/custom_shapes'; import { DefaultFill, textCoreConstants } from '../type/textCore'; @@ -26,10 +27,10 @@ class Renderer2D extends Renderer { this.canvas.style.display = 'none'; } - if (!this.elt.id) { - this.elt.id = `defaultCanvas${p5.sketchCount++}`; - } - this.elt.classList.add('p5Canvas'); + markP5Canvas( + this.elt, + this.elt.id || `defaultCanvas${p5.sketchCount++}` + ); // Extend renderer with methods of p5.Element with getters for (const p of Object.getOwnPropertyNames(Element.prototype)) { @@ -43,24 +44,10 @@ class Renderer2D extends Renderer { } // Set canvas size - this.elt.width = w * this._pixelDensity; - this.elt.height = h * this._pixelDensity; - this.elt.style.width = `${w}px`; - this.elt.style.height = `${h}px`; + setCanvasSize(this.elt, w, h, this._pixelDensity); // Attach canvas element to DOM - if (this._pInst._userNode) { - // user input node case - this._pInst._userNode.appendChild(this.elt); - } else { - //create main element - if (document.getElementsByTagName('main').length === 0) { - let m = document.createElement('main'); - document.body.appendChild(m); - } - //append canvas to main - document.getElementsByTagName('main')[0].appendChild(this.elt); - } + attachCanvas(this.elt, this._pInst._userNode); // Get and store drawing context this.drawingContext = this.canvas.getContext('2d', attributes); @@ -139,10 +126,7 @@ class Renderer2D extends Renderer { } } - this.canvas.width = w * this._pixelDensity; - this.canvas.height = h * this._pixelDensity; - this.canvas.style.width = `${w}px`; - this.canvas.style.height = `${h}px`; + setCanvasSize(this.canvas, w, h, this._pixelDensity); this.drawingContext.scale(this._pixelDensity, this._pixelDensity); // reset canvas properties diff --git a/src/core/p5.Renderer3D.js b/src/core/p5.Renderer3D.js index b01b4775e0..4c8a8ea53b 100644 --- a/src/core/p5.Renderer3D.js +++ b/src/core/p5.Renderer3D.js @@ -25,6 +25,7 @@ import { Texture } from '../webgl/p5.Texture'; import { makeFilterShader } from '../core/filterShaders'; import { getStrokeDefs } from '../webgl/enums'; import { markExperimental } from '../core/experimental'; +import { markP5Canvas, setCanvasSize, attachCanvas } from '#platform'; const { STROKE_CAP_ENUM, STROKE_JOIN_ENUM } = getStrokeDefs(() => ''); @@ -44,8 +45,7 @@ export class Renderer3D extends Renderer { // hide if offscreen buffer by default this.canvas.style.display = 'none'; } - this.elt.id = 'defaultCanvas0'; - this.elt.classList.add('p5Canvas'); + markP5Canvas(this.elt, 'defaultCanvas0'); // Set and return p5.Element this.wrappedElt = new Element(this.elt, this._pInst); @@ -69,25 +69,11 @@ export class Renderer3D extends Renderer { this.height = h; // Set canvas size - this.elt.width = w * this._pixelDensity; - this.elt.height = h * this._pixelDensity; - this.elt.style.width = `${w}px`; - this.elt.style.height = `${h}px`; + setCanvasSize(this.elt, w, h, this._pixelDensity); this._updateViewport(); // Attach canvas element to DOM - if (this._pInst._userNode) { - // user input node case - this._pInst._userNode.appendChild(this.elt); - } else { - //create main element - if (document.getElementsByTagName('main').length === 0) { - let m = document.createElement('main'); - document.body.appendChild(m); - } - //append canvas to main - document.getElementsByTagName('main')[0].appendChild(this.elt); - } + attachCanvas(this.elt, this._pInst._userNode); this.isP3D = true; //lets us know we're in 3d mode @@ -1315,10 +1301,7 @@ export class Renderer3D extends Renderer { this.width = w; this.height = h; - this.canvas.width = w * this._pixelDensity; - this.canvas.height = h * this._pixelDensity; - this.canvas.style.width = `${w}px`; - this.canvas.style.height = `${h}px`; + setCanvasSize(this.canvas, w, h, this._pixelDensity); this._updateViewport(); this._updateSize(); diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js index b5f6ad5fa5..7e9f44cfa1 100644 --- a/src/core/platform/browser.js +++ b/src/core/platform/browser.js @@ -43,3 +43,33 @@ export const getUserScript = () => { }; export const isCanvasElement = data => data instanceof HTMLCanvasElement; + +// TODO is this the right API? +export const markP5Canvas = (elt, id) => { + elt.id = id; + elt.classList.add('p5Canvas'); +}; + +// TODO is this the right API? +export const setCanvasSize = (elt, w, h, density) => { + elt.width = w * density; + elt.height = h * density; + elt.style.width = `${w}px`; + elt.style.height = `${h}px`; +}; + +// TODO is this the right API? +export const attachCanvas = (elt, userNode) => { + if (userNode) { + // user input node case + userNode.appendChild(elt); + } else { + //create main element + if (document.getElementsByTagName('main').length === 0) { + let m = document.createElement('main'); + document.body.appendChild(m); + } + //append canvas to main + document.getElementsByTagName('main')[0].appendChild(elt); + } +}; diff --git a/src/core/platform/node.js b/src/core/platform/node.js index 0a70249f1b..0e72ed1818 100644 --- a/src/core/platform/node.js +++ b/src/core/platform/node.js @@ -18,3 +18,17 @@ export const getUserScript = () => undefined; // This prop is added in the wgpu code so we can identify it here export const isCanvasElement = data => data?.isP5WGPUCanvas === true; + +// TODO is this the right API? +export const markP5Canvas = () => {}; + +// TODO is this the right API? +// TODO resize the window and surface once ngpu supports it +export const setCanvasSize = (elt, w, h, density) => { + elt.width = w * density; + elt.height = h * density; +}; + +// TODO is this the right API? +// No page to attach to on desktop +export const attachCanvas = () => {}; From 9406a1279c4c02fd0ca6f559c94f1b719cd79963 Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 20:05:55 -0500 Subject: [PATCH 11/13] Allow imagedata-shaped things too --- src/webgl/p5.Texture.js | 3 +-- src/webgpu/p5.RendererWebGPU.js | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/webgl/p5.Texture.js b/src/webgl/p5.Texture.js index 032ffeaff8..242880d4ec 100644 --- a/src/webgl/p5.Texture.js +++ b/src/webgl/p5.Texture.js @@ -72,8 +72,7 @@ class Texture { this.isSrcP5Image = obj instanceof Image; this.isSrcP5Graphics = obj instanceof Graphics; this.isSrcP5Renderer = obj instanceof Renderer; - this.isImageData = - typeof ImageData !== 'undefined' && obj instanceof ImageData; + this.isImageData = Boolean(obj?.width && obj?.height && obj?.data); this.isSrcMediaElement = typeof MediaElement !== 'undefined' && obj instanceof MediaElement; this.isSrcHTMLElement = diff --git a/src/webgpu/p5.RendererWebGPU.js b/src/webgpu/p5.RendererWebGPU.js index 7cf98d8e6c..972a534c1e 100644 --- a/src/webgpu/p5.RendererWebGPU.js +++ b/src/webgpu/p5.RendererWebGPU.js @@ -3162,6 +3162,18 @@ function rendererWebGPU(p5, fn) { } uploadTextureFromSource({ gpuTexture }, source) { + // Raw pixels, e.g. an ImageData + // TODO check if this fixes #8703 + if (source.data) { + this.uploadTextureFromData( + { gpuTexture }, + source.data, + source.width, + source.height + ); + return; + } + const isVideo = source instanceof HTMLVideoElement; // Chrome throws if a video has no decoded frame yet if (isVideo && source.readyState < 2) return; @@ -3200,6 +3212,19 @@ function rendererWebGPU(p5, fn) { this.flushDraw(); } + // Avoiding p5.Image use here for portability + _getEmptyTexture() { + if (!this._emptyTexture) { + // a plain white texture RGBA, full alpha, single pixel. + this._emptyTexture = new Texture(this, { + width: 1, + height: 1, + data: new Uint8ClampedArray([255, 255, 255, 255]) + }); + } + return this._emptyTexture; + } + setTextureParams(_texture) {} getSampler(texture) { From d6f3351a99ac296ca0350028f2d767ec069b0a9d Mon Sep 17 00:00:00 2001 From: Dave Pagurek Date: Tue, 1 Dec 2026 20:16:25 -0500 Subject: [PATCH 12/13] right, doc comments get attached to stuff and show up in the reference, oops --- src/core/platform/browser.js | 10 +++++----- src/core/platform/node.js | 6 +++--- src/friendly_errors/stacktrace.js | 2 +- src/webgpu/p5.RendererWebGPU.js | 1 - 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js index 7e9f44cfa1..f22242d20e 100644 --- a/src/core/platform/browser.js +++ b/src/core/platform/browser.js @@ -1,8 +1,8 @@ -/** - * Browser adapter. Everything p5 needs from its host environment should go - * through this module, so that non-browser builds can swap in - * alternate implementations instead. - */ +/* +Browser adapter. Everything p5 needs from its host environment should go +through this module, so that non-browser builds can swap in +alternate implementations instead. +*/ // make a promise that resolves when the document is ready export const waitForDocumentReady = () => { diff --git a/src/core/platform/node.js b/src/core/platform/node.js index 0e72ed1818..44c232ff5c 100644 --- a/src/core/platform/node.js +++ b/src/core/platform/node.js @@ -1,6 +1,6 @@ -/** - * Node adapter, used in place of `platform.js` by the p5.node build. - */ +/* +Node adapter, used in place of `platform.js` by the p5.node build. +*/ // There is no document to wait for export const waitForDocumentReady = () => Promise.resolve(); diff --git a/src/friendly_errors/stacktrace.js b/src/friendly_errors/stacktrace.js index 9a142fa237..4d03a49788 100644 --- a/src/friendly_errors/stacktrace.js +++ b/src/friendly_errors/stacktrace.js @@ -261,7 +261,7 @@ export const errorStackParser = new ErrorStackParser(); * @private * @param {Error} error * @param {Array} stacktrace - * @param {Function} p5 the p5 class, which holds the FES log cache + * @param p5 The p5 global, which has the log cache * * @returns {Array} An array with two elements, [isInternal, friendlyStack] * isInternal: a boolean value indicating whether the error diff --git a/src/webgpu/p5.RendererWebGPU.js b/src/webgpu/p5.RendererWebGPU.js index 972a534c1e..2a68f49f04 100644 --- a/src/webgpu/p5.RendererWebGPU.js +++ b/src/webgpu/p5.RendererWebGPU.js @@ -3215,7 +3215,6 @@ function rendererWebGPU(p5, fn) { // Avoiding p5.Image use here for portability _getEmptyTexture() { if (!this._emptyTexture) { - // a plain white texture RGBA, full alpha, single pixel. this._emptyTexture = new Texture(this, { width: 1, height: 1, From 7c8c8c4158c78cef848d0d72c80c3d17c4323f4c Mon Sep 17 00:00:00 2001 From: limzykenneth Date: Wed, 2 Dec 2026 15:58:03 +0000 Subject: [PATCH 13/13] Add a bit of scaffolding for testing node.js mode --- package.json | 1 + preview/node/sketch.mjs | 13 +++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 preview/node/sketch.mjs diff --git a/package.json b/package.json index b4613315b9..790e26bb80 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "scripts": { "build": "rolldown -c", "dev": "vite preview/", + "dev:node": "concurrently -n build,server \"rolldown -c -w\" \"node --watch preview/node/sketch.mjs\"", "dev:global": "concurrently -n build,server \"rolldown -c -w\" \"npx vite preview/global/\"", "docs": "documentation build ./src/**/*.js ./src/**/**/*.js --shallow -o ./docs/data.json && node ./utils/convert.mjs", "bench": "vitest bench", diff --git a/preview/node/sketch.mjs b/preview/node/sketch.mjs new file mode 100644 index 0000000000..116ef183b7 --- /dev/null +++ b/preview/node/sketch.mjs @@ -0,0 +1,13 @@ +// import p5 from "../../dist/app.node.js"; +// import p5 from "../../lib/p5.node.esm.js"; +import webgpu from "../../dist/webgpu/index.js"; + +p5.registerAddon(webgpu); + +const sketch = function (p) { + p.setup = function () { + p.createCanvas(800, 600, p.WEBGPU); + }; +}; + +new p5(sketch);