UNPKG

p5

Version:

[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)

1,261 lines (1,260 loc) • 41.5 kB
import { Bt as REMOVE, Cn as _DEFAULT_FILL, Dn as constants_exports, Kt as ROUND, Tn as _DEFAULT_STROKE, Wt as RIGHT, g as CENTER, gn as VERSION, m as BOTTOM, s as BASELINE, st as LEFT, u as BLEND, vn as WEBGL } from "./constants-DA50zLWL.js"; import transform from "./core/transform.js"; import structure from "./core/structure.js"; import environment from "./core/environment.js"; import { u as RGBP3 } from "./creating_reading-CHnSLr--.js"; import { Element } from "./dom/p5.Element.js"; import { n as renderer, r as Image, t as Renderer } from "./p5.Renderer-DJhbZi26.js"; import { PrimitiveToPath2DConverter } from "./shape/custom_shapes.js"; import { MediaElement } from "./dom/p5.MediaElement.js"; import { n as rendering, v as Graphics, y as graphics } from "./rendering-BHEDmo0B.js"; import { Matrix } from "./math/Matrices/Matrix.js"; import "./math/p5.Matrix.js"; import { DefaultFill, textCoreConstants } from "./type/textCore.js"; import FilterRenderer2D from "./image/filterRenderer2D.js"; import loading from "./core/loading.js"; //#region src/core/p5.Renderer2D.js var Renderer2D = class extends Renderer { constructor(pInst, w, h, isMainCanvas, elt, attributes = {}) { super(pInst, w, h, isMainCanvas); this.canvas = this.elt = elt || document.createElement("canvas"); if (isMainCanvas) { this._pInst._curElement = this; this._pInst.canvas = this.canvas; } else this.canvas.style.display = "none"; if (!this.elt.id) this.elt.id = `defaultCanvas${p5.sketchCount++}`; this.elt.classList.add("p5Canvas"); for (const p of Object.getOwnPropertyNames(Element.prototype)) if (p !== "constructor" && p[0] !== "_") Object.defineProperty(this, p, { get() { return this.wrappedElt[p]; } }); this.elt.width = w * this._pixelDensity; this.elt.height = h * this._pixelDensity; this.elt.style.width = `${w}px`; this.elt.style.height = `${h}px`; if (this._pInst._userNode) this._pInst._userNode.appendChild(this.elt); else { if (document.getElementsByTagName("main").length === 0) { let m = document.createElement("main"); document.body.appendChild(m); } document.getElementsByTagName("main")[0].appendChild(this.elt); } this.drawingContext = this.canvas.getContext("2d", attributes); if (attributes.colorSpace === "display-p3") this.states.colorMode = RGBP3; this.scale(this._pixelDensity, this._pixelDensity); this.wrappedElt = new Element(this.elt, this._pInst); this.clipPath = null; } get filterRenderer() { if (!this._filterRenderer) this._filterRenderer = new FilterRenderer2D(this); return this._filterRenderer; } remove() { this.wrappedElt.remove(); this.wrappedElt = null; this.canvas = null; this.elt = null; } getFilterGraphicsLayer() { if (!this.filterGraphicsLayer) { const pInst = this._pInst; this.filterGraphicsLayer = new Graphics(this.width, this.height, WEBGL, pInst); } if (this.filterGraphicsLayer.width !== this.width || this.filterGraphicsLayer.height !== this.height) this.filterGraphicsLayer.resizeCanvas(this.width, this.height); if (this.filterGraphicsLayer.pixelDensity() !== this._pInst.pixelDensity()) this.filterGraphicsLayer.pixelDensity(this._pInst.pixelDensity()); return this.filterGraphicsLayer; } _applyDefaults() { this.states.setValue("_cachedFillStyle", void 0); this.states.setValue("_cachedStrokeStyle", void 0); this._cachedBlendMode = BLEND; this._setFill(_DEFAULT_FILL); this._setStroke(_DEFAULT_STROKE); this.drawingContext.lineCap = ROUND; this.drawingContext.font = "normal 12px sans-serif"; } resize(w, h) { super.resize(w, h); const props = {}; for (const key in this.drawingContext) { const val = this.drawingContext[key]; if (typeof val !== "object" && typeof val !== "function") props[key] = val; } this.canvas.width = w * this._pixelDensity; this.canvas.height = h * this._pixelDensity; this.canvas.style.width = `${w}px`; this.canvas.style.height = `${h}px`; this.drawingContext.scale(this._pixelDensity, this._pixelDensity); for (const savedKey in props) try { this.drawingContext[savedKey] = props[savedKey]; } catch {} } background(...args) { if (args.length === 0) return this; this.push(); this.resetMatrix(); if (args[0] instanceof Image) { const img = args[0]; if (args[1] >= 0) this.drawingContext.globalAlpha = args[1] / 255; this._pInst.image(img, 0, 0, this.width, this.height); } else { const color = this._pInst.color(...args); if (this._pInst._addAccsOutput?.()) this._pInst._accsBackground?.(color._getRGBA([ 255, 255, 255, 255 ])); const newFill = color.toString(); this._setFill(newFill); if (this._isErasing) this.blendMode(this._cachedBlendMode); this.drawingContext.fillRect(0, 0, this.width, this.height); if (this._isErasing) this._pInst.erase(); } this.pop(); return this; } clear() { this.drawingContext.save(); this.resetMatrix(); this.drawingContext.clearRect(0, 0, this.width, this.height); this.drawingContext.restore(); } fill(...args) { super.fill(...args); const color = this.states.fillColor; if (args.length === 0) return color; this._setFill(color.toString()); if (this._pInst._addAccsOutput?.()) this._pInst._accsCanvasColors?.("fill", color._getRGBA([ 255, 255, 255, 255 ])); } stroke(...args) { super.stroke(...args); const color = this.states.strokeColor; if (args.length === 0) return color; this._setStroke(color.toString()); if (this._pInst._addAccsOutput?.()) this._pInst._accsCanvasColors?.("stroke", color._getRGBA([ 255, 255, 255, 255 ])); } erase(opacityFill, opacityStroke) { if (!this._isErasing) { this.states.setValue("_cachedFillStyle", this.drawingContext.fillStyle); const newFill = this._pInst.color(255, opacityFill).toString(); this.drawingContext.fillStyle = newFill; this.states.setValue("_cachedStrokeStyle", this.drawingContext.strokeStyle); const newStroke = this._pInst.color(255, opacityStroke).toString(); this.drawingContext.strokeStyle = newStroke; const tempBlendMode = this._cachedBlendMode; this.blendMode(REMOVE); this._cachedBlendMode = tempBlendMode; this._isErasing = true; } } noErase() { if (this._isErasing) { this.drawingContext.fillStyle = this.states._cachedFillStyle; this.drawingContext.strokeStyle = this.states._cachedStrokeStyle; this.blendMode(this._cachedBlendMode); this._isErasing = false; } } drawShape(shape) { const visitor = new PrimitiveToPath2DConverter({ strokeWeight: this.states.strokeWeight, hasFill: !this._clipping && !!this.states.fillColor, hasStroke: !this._clipping && !!this.states.strokeColor }); shape.accept(visitor); if (this._clipping) { const currentTransform = this.drawingContext.getTransform(); const relativeTransform = this._clipBaseTransform.inverse().multiply(currentTransform); this.clipPath.addPath(visitor.path, relativeTransform); this.clipPath.closePath(); } else { if (this.states.fillColor) this.drawingContext.fill(visitor.fillPath || visitor.path); if (this.states.strokeColor) this.drawingContext.stroke(visitor.strokePath || visitor.path); } } beginClip(options = {}) { super.beginClip(options); this._clipBaseTransform = this.drawingContext.getTransform(); this.states.setValue("_cachedFillStyle", this.drawingContext.fillStyle); const newFill = this._pInst.color(255, 0).toString(); this.drawingContext.fillStyle = newFill; this.states.setValue("_cachedStrokeStyle", this.drawingContext.strokeStyle); const newStroke = this._pInst.color(255, 0).toString(); this.drawingContext.strokeStyle = newStroke; const tempBlendMode = this._cachedBlendMode; this.blendMode(BLEND); this._cachedBlendMode = tempBlendMode; this.clipPath = new Path2D(); this._clipBaseTransform = this.drawingContext.getTransform(); if (this._clipInvert) { this.clipPath.moveTo(-2 * this.width, -2 * this.height); this.clipPath.lineTo(-2 * this.width, 2 * this.height); this.clipPath.lineTo(2 * this.width, 2 * this.height); this.clipPath.lineTo(2 * this.width, -2 * this.height); this.clipPath.closePath(); } } endClip() { const savedTransform = this.drawingContext.getTransform(); this.drawingContext.setTransform(this._clipBaseTransform); this.drawingContext.clip(this.clipPath); this.drawingContext.setTransform(savedTransform); this.clipPath = null; super.endClip(); this.drawingContext.fillStyle = this.states._cachedFillStyle; this.drawingContext.strokeStyle = this.states._cachedStrokeStyle; this.blendMode(this._cachedBlendMode); } image(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { let cnv; if (img.gifProperties) img._animateGif(this._pInst); try { if (img instanceof MediaElement) img._ensureCanvas(); if (this.states.tint && img.canvas) cnv = this._getTintedImageCanvas(img); if (!cnv) cnv = img.canvas || img.elt; let s = 1; if (img.width && img.width > 0) s = cnv.width / img.width; if (this._isErasing) this.blendMode(this._cachedBlendMode); this.drawingContext.drawImage(cnv, s * sx, s * sy, s * sWidth, s * sHeight, dx, dy, dWidth, dHeight); if (this._isErasing) this._pInst.erase(); } catch (e) { if (e.name !== "NS_ERROR_NOT_AVAILABLE") throw e; } } _getTintedImageCanvas(img) { if (!img.canvas) return img; if (!img.tintCanvas) img.tintCanvas = document.createElement("canvas"); if (img.tintCanvas.width !== img.canvas.width) img.tintCanvas.width = img.canvas.width; if (img.tintCanvas.height !== img.canvas.height) img.tintCanvas.height = img.canvas.height; const ctx = img.tintCanvas.getContext("2d"); ctx.save(); ctx.clearRect(0, 0, img.canvas.width, img.canvas.height); const tint = this.states.tint._getRGBA([ 255, 255, 255, 255 ]); if (tint[0] < 255 || tint[1] < 255 || tint[2] < 255) { ctx.drawImage(img.canvas, 0, 0); ctx.globalCompositeOperation = "luminosity"; ctx.drawImage(img.canvas, 0, 0); ctx.globalCompositeOperation = "color"; ctx.drawImage(img.canvas, 0, 0); ctx.globalCompositeOperation = "multiply"; ctx.fillStyle = `rgb(${tint.slice(0, 3).join(", ")})`; ctx.fillRect(0, 0, img.canvas.width, img.canvas.height); ctx.globalCompositeOperation = "destination-in"; ctx.globalAlpha = tint[3] / 255; ctx.drawImage(img.canvas, 0, 0); } else { ctx.globalAlpha = tint[3] / 255; ctx.drawImage(img.canvas, 0, 0); } ctx.restore(); return img.tintCanvas; } blendMode(mode) { if (typeof mode === "undefined") return this._cachedBlendMode; if (mode === "subtract") console.warn("blendMode(SUBTRACT) only works in WEBGL mode."); else if (mode === "source-over" || mode === "destination-out" || mode === "darken" || mode === "lighten" || mode === "difference" || mode === "multiply" || mode === "exclusion" || mode === "screen" || mode === "copy" || mode === "overlay" || mode === "hard-light" || mode === "soft-light" || mode === "color-dodge" || mode === "color-burn" || mode === "lighter") { this._cachedBlendMode = mode; this.drawingContext.globalCompositeOperation = mode; } else throw new Error(`Mode ${mode} not recognized.`); } blend(...args) { const currBlend = this.drawingContext.globalCompositeOperation; const blendMode = args[args.length - 1]; const copyArgs = Array.prototype.slice.call(args, 0, args.length - 1); this.drawingContext.globalCompositeOperation = blendMode; p5.prototype.copy.apply(this, copyArgs); this.drawingContext.globalCompositeOperation = currBlend; } _getPixel(x, y) { let imageData, index; imageData = this.drawingContext.getImageData(x, y, 1, 1).data; index = 0; return [ imageData[index + 0], imageData[index + 1], imageData[index + 2], imageData[index + 3] ]; } loadPixels() { const pd = this._pixelDensity; const w = this.width * pd; const h = this.height * pd; const imageData = this.drawingContext.getImageData(0, 0, w, h); this.imageData = imageData; this.pixels = imageData.data; } set(x, y, imgOrCol) { x = Math.floor(x); y = Math.floor(y); if (imgOrCol instanceof Graphics || imgOrCol instanceof Image) { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale(this._pixelDensity, this._pixelDensity); const width = imgOrCol.width; const height = imgOrCol.height; this.drawingContext.clearRect(x, y, width, height); this.drawingContext.drawImage(imgOrCol.canvas, x, y, width, height); this.drawingContext.restore(); } else { let r = 0, g = 0, b = 0, a = 0; let idx = 4 * (y * this._pixelDensity * (this.width * this._pixelDensity) + x * this._pixelDensity); if (!this.imageData) this.loadPixels(); if (typeof imgOrCol === "number") { if (idx < this.pixels.length) { r = imgOrCol; g = imgOrCol; b = imgOrCol; a = 255; } } else if (Array.isArray(imgOrCol)) { if (imgOrCol.length < 4) throw new Error("pixel array must be of the form [R, G, B, A]"); if (idx < this.pixels.length) { r = imgOrCol[0]; g = imgOrCol[1]; b = imgOrCol[2]; a = imgOrCol[3]; } } else if (imgOrCol instanceof p5.Color) { if (idx < this.pixels.length) [r, g, b, a] = imgOrCol._getRGBA([ 255, 255, 255, 255 ]); } for (let i = 0; i < this._pixelDensity; i++) for (let j = 0; j < this._pixelDensity; j++) { idx = 4 * ((y * this._pixelDensity + j) * this.width * this._pixelDensity + (x * this._pixelDensity + i)); this.pixels[idx] = r; this.pixels[idx + 1] = g; this.pixels[idx + 2] = b; this.pixels[idx + 3] = a; } } } updatePixels(x, y, w, h) { const pd = this._pixelDensity; if (x === void 0 && y === void 0 && w === void 0 && h === void 0) { x = 0; y = 0; w = this.width; h = this.height; } x *= pd; y *= pd; w *= pd; h *= pd; if (this.gifProperties) this.gifProperties.frames[this.gifProperties.displayIndex].image = this.imageData; this.drawingContext.putImageData(this.imageData, 0, 0, x, y, w, h); } arc(x, y, w, h, start, stop, mode) { const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.arcPrimitive(x, y, w, h, start, stop, mode); shape.endShape(); this.drawShape(shape); return this; } ellipse(args) { const x = parseFloat(args[0]), y = parseFloat(args[1]), w = parseFloat(args[2]), h = parseFloat(args[3]); const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.ellipsePrimitive(x, y, w, h); shape.endShape(); this.drawShape(shape); return this; } line(x1, y1, x2, y2) { const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.line(x1, y1, x2, y2); shape.endShape(); this.drawShape(shape); return this; } point(x, y) { const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.point(x, y); shape.endShape(); this.drawShape(shape); return this; } quad(x1, y1, x2, y2, x3, y3, x4, y4) { const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.quad(x1, y1, x2, y2, x3, y3, x4, y4); shape.endShape(); this.drawShape(shape); return this; } rect(args) { const x = args[0]; const y = args[1]; const w = args[2]; const h = args[3]; let tl = args[4]; let tr = args[5]; let br = args[6]; let bl = args[7]; const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.rectPrimitive(x, y, w, h, tl, tr, br, bl); shape.endShape(); this.drawShape(shape); return this; } triangle(args) { const x1 = args[0], y1 = args[1]; const x2 = args[2], y2 = args[3]; const x3 = args[4], y3 = args[5]; const shape = new p5.Shape({ position: new p5.Vector(0, 0) }); shape.beginShape(); shape.triangle(x1, y1, x2, y2, x3, y3); shape.endShape(); this.drawShape(shape); return this; } strokeCap(cap) { if (typeof cap === "undefined") return this.drawingContext.lineCap; if (cap === "round" || cap === "butt" || cap === "square") this.drawingContext.lineCap = cap; return this; } strokeJoin(join) { if (typeof join === "undefined") return this.drawingContext.lineJoin; if (join === "round" || join === "bevel" || join === "miter") this.drawingContext.lineJoin = join; return this; } strokeWeight(w) { super.strokeWeight(w); if (typeof w === "undefined") return this.states.strokeWeight; if (w === 0) this.drawingContext.lineWidth = 1e-4; else this.drawingContext.lineWidth = w; return this; } _getFill() { if (!this.states._cachedFillStyle) this.states.setValue("_cachedFillStyle", this.drawingContext.fillStyle); return this.states._cachedFillStyle; } _setFill(fillStyle) { if (fillStyle !== this.states._cachedFillStyle) { this.drawingContext.fillStyle = fillStyle; this.states.setValue("_cachedFillStyle", fillStyle); } } _getStroke() { if (!this.states._cachedStrokeStyle) this.states.setValue("_cachedStrokeStyle", this.drawingContext.strokeStyle); return this.states._cachedStrokeStyle; } _setStroke(strokeStyle) { if (strokeStyle !== this.states._cachedStrokeStyle) { this.drawingContext.strokeStyle = strokeStyle; this.states.setValue("_cachedStrokeStyle", strokeStyle); } } applyMatrix(a, b, c, d, e, f) { this.drawingContext.transform(a, b, c, d, e, f); } getWorldToScreenMatrix() { let domMatrix = new DOMMatrix().scale(1 / this._pixelDensity).multiply(this.drawingContext.getTransform()); return new Matrix(domMatrix.toFloat32Array()); } resetMatrix() { this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale(this._pixelDensity, this._pixelDensity); return this; } rotate(rad) { this.drawingContext.rotate(rad); return this; } scale(x, y) { if (typeof x === "object" && "x" in x && "y" in x) { y = x.y; x = x.x; } this.drawingContext.scale(x, y); return this; } translate(x, y) { if (typeof x === "object" && "x" in x && "y" in x) { y = x.y; x = x.x; } this.drawingContext.translate(x, y); return this; } push() { this.drawingContext.save(); return super.push(); } pop(style) { this.drawingContext.restore(); super.pop(style); } textCanvas() { return this.canvas; } textDrawingContext() { return this.drawingContext; } _renderText(text, x, y, maxY, minY) { let states = this.states; let context = this.textDrawingContext(); if (y < minY || y >= maxY) return; this.push(); if (states.strokeColor && states.strokeSet) context.strokeText(text, x, y); if (!this._clipping && states.fillColor) { if (!states.fillSet) this._setFill(DefaultFill); context.fillText(text, x, y); } this.pop(); } _positionLines(x, y, width, height, lines) { let { textLeading, textAlign } = this.states; let adjustedX, lineData = new Array(lines.length); let adjustedW = typeof width === "undefined" ? 0 : width; let adjustedH = typeof height === "undefined" ? 0 : height; for (let i = 0; i < lines.length; i++) { switch (textAlign) { case textCoreConstants.START: throw new Error("textBounds: START not yet supported for textAlign"); case LEFT: adjustedX = x; break; case CENTER: adjustedX = x + adjustedW / 2; break; case RIGHT: adjustedX = x + adjustedW; break; case textCoreConstants.END: throw new Error("textBounds: END not yet supported for textAlign"); } lineData[i] = { text: lines[i], x: adjustedX, y: y + i * textLeading }; } return this._yAlignOffset(lineData, adjustedH); } _yAlignOffset(dataArr, height) { if (typeof height === "undefined") throw Error("_yAlignOffset: height is required"); let { textLeading, textBaseline } = this.states; let yOff = 0; let ydiff = height - textLeading * (dataArr.length - 1); switch (textBaseline) { case "top": break; case BASELINE: break; case textCoreConstants._CTX_MIDDLE: yOff = ydiff / 2 + this._middleAlignOffset(); break; case BOTTOM: yOff = ydiff; break; case textCoreConstants.IDEOGRAPHIC: console.warn("textBounds: IDEOGRAPHIC not yet supported for textBaseline"); break; case textCoreConstants.HANGING: console.warn("textBounds: HANGING not yet supported for textBaseline"); } dataArr.forEach((ele) => ele.y += yOff); return dataArr; } }; function renderer2D(p5, fn) { /** * p5.Renderer2D * The 2D graphics canvas renderer class. * extends p5.Renderer * @private */ p5.Renderer2D = Renderer2D; p5.renderers["p2d"] = Renderer2D; p5.renderers["p2d-p3"] = new Proxy(Renderer2D, { construct(target, [pInst, w, h, isMainCanvas, elt]) { return new target(pInst, w, h, isMainCanvas, elt, { colorSpace: "display-p3" }); } }); } //#endregion //#region src/core/main.js /** * @module Structure * @submodule Structure * @for p5 */ /** * This is the p5 instance constructor. * * A p5 instance holds all the properties and methods related to * a p5 sketch. It expects an incoming sketch closure and it can also * take an optional node parameter for attaching the generated p5 canvas * to a node. The sketch closure takes the newly created p5 instance as * its sole argument and may optionally set an asynchronous function * using `async/await`, along with the standard <a href="#/p5/setup">setup()</a>, * and/or <a href="#/p5/setup">setup()</a>, and/or <a href="#/p5/draw">draw()</a> * properties on it for running a sketch. * * A p5 sketch can run in "global" or "instance" mode: * "global" - all properties and methods are attached to the window * "instance" - all properties and methods are bound to this p5 object * * @class p5 * @param {function(p5)} sketch a closure that can set optional <a href="#/p5/preload">preload()</a>, * <a href="#/p5/setup">setup()</a>, and/or <a href="#/p5/draw">draw()</a> properties on the * given p5 instance * @param {String|HTMLElement} [node] element to attach canvas to * @return {p5} a p5 instance */ var p5 = class p5 { static loadingAnimation = true; static VERSION = VERSION; static instance = null; static sketchCount = 0; static lifecycleHooks = { presetup: [], postsetup: [], predraw: [], postdraw: [], remove: [] }; static _checkForUserDefinedFunctions = () => {}; static _friendlyFileLoadError = () => {}; static _friendlyError = () => {}; static _checkForUserDefinedFunctions = () => {}; static FES = { log: () => () => {}, warn: () => () => {}, error: () => () => {}, debug: () => () => {}, info: () => () => {} }; constructor(sketch, node) { if (p5.decorations.size > 0) { decorateClass(p5, p5.decorations, "p5"); p5.decorations.clear(); } this.hitCriticalError = false; this._setupDone = false; this._userNode = node; this._curElement = null; this._elements = []; this._glAttributes = null; this._webgpuAttributes = null; this._requestAnimId = 0; this._isGlobal = false; this._loop = true; this._startListener = null; this._initializeInstanceVariables(); this._events = {}; this._removeAbortController = new AbortController(); this._removeSignal = this._removeAbortController.signal; this._millisStart = -1; this._recording = false; this._lcg_random_state = null; this._gaussian_previous = false; this._updateWindowSize(); const bindGlobal = createBindGlobal(this); if (!sketch) { this._isGlobal = true; if (window.hitCriticalError) return; p5.instance = this; for (const p of Object.getOwnPropertyNames(p5.prototype)) { if (p[0] === "_") continue; bindGlobal(p); } const protectedProperties = ["constructor", "length"]; for (const p in this) if (this.hasOwnProperty(p)) { if (p[0] === "_" || protectedProperties.includes(p)) continue; bindGlobal(p); } } else { sketch(this); p5._checkForUserDefinedFunctions(this); } const focusHandler = () => { this.focused = true; }; const blurHandler = () => { this.focused = false; }; if (typeof window !== "undefined") { window.addEventListener("focus", focusHandler, { signal: this._removeSignal }); window.addEventListener("blur", blurHandler, { signal: this._removeSignal }); if (document.readyState === "complete") this.#_start(); else { this._startListener = this.#_start.bind(this); window.addEventListener("load", this._startListener, false); } } else this.#_start(); } get pixels() { return this._renderer?.pixels; } get drawingContext() { return this._renderer?.drawingContext; } static _registeredAddons = /* @__PURE__ */ new Set(); static registerAddon(addon) { const lifecycles = {}; if (p5._registeredAddons.has(addon)) return; p5._registeredAddons.add(addon); addon(p5, p5.prototype, lifecycles); const validLifecycles = Object.keys(p5.lifecycleHooks); for (const name of validLifecycles) if (typeof lifecycles[name] === "function") p5.lifecycleHooks[name].push(lifecycles[name]); } static decorations = /* @__PURE__ */ new Map(); static registerDecorator(pattern, decoration) { if (typeof pattern === "string") { const patternStr = pattern; pattern = ({ path }) => patternStr === path; } else if (Array.isArray(pattern) && pattern.every((value) => typeof value === "string")) { const patternArray = pattern; pattern = ({ path }) => patternArray.includes(path); } else if (typeof pattern !== "function") throw new Error("Decorator matching pattern must be a function, a string, or an array of strings"); p5.decorations.set(pattern, decoration); } #customActions = {}; _customActions = new Proxy({}, { get: (target, prop) => { if (!this.#customActions[prop]) { const context = this._isGlobal ? window : this; if (typeof context[prop] === "function") this.#customActions[prop] = context[prop].bind(this); } return this.#customActions[prop]; } }); async #_start() { if (this.hitCriticalError) return; if (this._userNode) { if (typeof this._userNode === "string") this._userNode = document.getElementById(this._userNode); } try { await this.#_setup(); } catch (error) { if (this._isSketchLoading) await this._runLifecycleHook("postsetup"); throw error; } if (this.hitCriticalError) return; if (!this._recording) this._draw(); } async #_setup() { await this._runLifecycleHook("presetup"); if (this.hitCriticalError) return; if (typeof window !== "undefined") this.createCanvas(100, 100, "p2d"); this._millisStart = globalThis.performance.now(); const context = this._isGlobal ? window : this; try { if (typeof context.setup === "function") await context.setup(); } catch (error) { await this._runLifecycleHook("postsetup"); throw error; } if (this.hitCriticalError) return; if (typeof document !== "undefined") { const canvases = document.getElementsByTagName("canvas"); for (const k of canvases) { k.style.touchAction = "none"; if (k.dataset.hidden === "true") { k.style.visibility = ""; delete k.dataset.hidden; } } } this._lastTargetFrameTime = globalThis.performance.now(); this._lastRealFrameTime = globalThis.performance.now(); this._setupDone = true; if (this._accessibleOutputs.grid || this._accessibleOutputs.text) this._updateAccsOutput(); await this._runLifecycleHook("postsetup"); this._millisStart = globalThis.performance.now(); } async _draw(requestAnimationFrameTimestamp) { if (this.hitCriticalError) return; const now = requestAnimationFrameTimestamp || globalThis.performance.now(); const timeSinceLastFrame = now - this._lastTargetFrameTime; const targetTimeBetweenFrames = 1e3 / this._targetFrameRate; if (!this._loop || timeSinceLastFrame >= targetTimeBetweenFrames - 5) { this.deltaTime = now - this._lastRealFrameTime; this._frameRate = 1e3 / this.deltaTime; await this.redraw(); this._lastTargetFrameTime = Math.max(this._lastTargetFrameTime + targetTimeBetweenFrames, now); this._lastRealFrameTime = now; if (typeof this._updateMouseCoords !== "undefined") { this._updateMouseCoords(); this.movedX = 0; this.movedY = 0; } } if (this._loop) { const boundDraw = this._draw.bind(this); this._requestAnimId = typeof window !== "undefined" ? window.requestAnimationFrame(boundDraw) : setImmediate(boundDraw); } } /** * Removes the sketch from the web page. * * Calling `remove()` stops the draw loop and removes any HTML elements * created by the sketch, including the canvas. A new sketch can be * created by using the <a href="#/p5/p5">p5()</a> constructor, as in * `new p5()`. * * @example * // Double-click to remove the canvas. * * function setup() { * createCanvas(100, 100); * * describe( * 'A white circle on a gray background. The circle follows the mouse as the user moves. The sketch disappears when the user double-clicks.' * ); * } * * function draw() { * // Paint the background repeatedly. * background(200); * * // Draw circles repeatedly. * circle(mouseX, mouseY, 40); * } * * // Remove the sketch when the user double-clicks. * function doubleClicked() { * remove(); * } */ async remove() { if (this._startListener) window.removeEventListener("load", this._startListener, false); if (this._curElement) { this._loop = false; if (this._requestAnimId) window.cancelAnimationFrame(this._requestAnimId); this._removeAbortController.abort(); const elementsToRemove = this._elements.slice(); for (const e of elementsToRemove) e.remove(); await this._runLifecycleHook("remove"); } if (this._isGlobal) { for (const p in p5.prototype) try { delete window[p]; } catch { window[p] = void 0; } for (const p2 in this) if (this.hasOwnProperty(p2)) try { delete window[p2]; } catch { window[p2] = void 0; } p5.instance = null; } } async _runLifecycleHook(hookName) { await Promise.all(p5.lifecycleHooks[hookName].map((hook) => { return hook.call(this); })); } _initializeInstanceVariables() { this._accessibleOutputs = { text: false, grid: false, textLabel: false, gridLabel: false }; this._styles = []; this._downKeys = {}; this._downKeyCodes = {}; } }; for (const k in constants_exports) p5.prototype[k] = constants_exports[k]; function createBindGlobal(instance) { return function bindGlobal(property) { if (property === "constructor") return; const instanceDescriptor = Object.getOwnPropertyDescriptor(instance, property); const prototypeDescriptor = Object.getOwnPropertyDescriptor(p5.prototype, property); const hasGetter = instanceDescriptor && instanceDescriptor.get || prototypeDescriptor && prototypeDescriptor.get; let isPrototypeFunction = false; let isConstant = false; let constantValue; if (!hasGetter) { const prototypeValue = p5.prototype[property]; isPrototypeFunction = typeof prototypeValue === "function"; if (!isPrototypeFunction && constants_exports[property] !== void 0) { isConstant = true; constantValue = prototypeValue; } } if (isPrototypeFunction) { const boundFunction = p5.prototype[property].bind(instance); Object.defineProperty(window, property, { configurable: true, enumerable: true, value: boundFunction }); } else if (isConstant) Object.defineProperty(window, property, { configurable: true, enumerable: true, value: constantValue }); else if (hasGetter || !isPrototypeFunction) { let lastFunction = null; let boundFunction = null; let isFunction = null; Object.defineProperty(window, property, { configurable: true, enumerable: true, get: () => { const currentValue = instance[property]; if (isFunction === null) { isFunction = typeof currentValue === "function"; if (isFunction) { lastFunction = currentValue; boundFunction = currentValue.bind(instance); return boundFunction; } else return currentValue; } else if (isFunction) { if (currentValue !== lastFunction) { lastFunction = currentValue; boundFunction = currentValue.bind(instance); } return boundFunction; } else return currentValue; } }); } }; } function copyFunctionProperties(original, decorated) { if (typeof original !== "function" || typeof decorated !== "function" || original === decorated) return; for (const key of Object.keys(original)) if (!(key in decorated)) decorated[key] = original[key]; } function decorateClass(Target, decorations, path) { for (const key in Target) if (!key.startsWith("_")) { for (const [pattern, decorator] of decorations) if (pattern({ path: `${path}.${key}` })) { if (typeof Target[key] === "function") { const result = decorator(Target[key], { kind: "method", name: key, static: true }); if (result) { copyFunctionProperties(Target[key], result); Object.defineProperty(Target, key, { enumerable: true, writable: true, value: result }); } } else { const result = decorator(void 0, { kind: "field", name: key, static: true }); if (result && typeof result === "function") Target[key] = result(Target[key]); } } if (typeof Target[key] === "function" && Target[key].prototype) decorateClass(Target[key], decorations, `${path}.${key}`); } for (const member of Object.getOwnPropertyNames(Target.prototype)) if (member !== "constructor" && !member.startsWith("_")) { for (const [pattern, decorator] of decorations) if (pattern({ path: `${path}.prototype.${member}` })) { if (typeof Target.prototype[member] === "function") { const result = decorator(Target.prototype[member], { kind: "method", name: member, static: false }); if (result) { copyFunctionProperties(Target.prototype[member], result); Object.defineProperty(Target.prototype, member, { enumerable: true, writable: true, value: result }); } } else { const descriptor = Object.getOwnPropertyDescriptor(Target.prototype, member); if (descriptor.hasOwnProperty("value")) { const result = decorator(void 0, { kind: "field", name: member, static: false }); Object.defineProperty(Target.prototype, member, { enumerable: true, writable: true, value: result && typeof result === "function" ? result(Target.prototype[member]) : Target.prototype[member] }); } else { const { get, set } = descriptor; const getterResult = decorator(get, { kind: "getter", name: member, static: false }); const setterResult = decorator(set, { kind: "setter", name: member, static: false }); Object.defineProperty(Target.prototype, member, { enumerable: true, get: getterResult ?? get, set: setterResult ?? set }); } } } } } p5.registerAddon(transform); p5.registerAddon(structure); p5.registerAddon(environment); p5.registerAddon(rendering); p5.registerAddon(renderer); p5.registerAddon(renderer2D); p5.registerAddon(graphics); if (typeof window !== "undefined") p5.registerAddon(loading); /** * A function that's called once when the sketch begins running. * * Declaring the function `setup()` sets a code block to run once * automatically when the sketch starts running. It's used to perform * setup tasks such as creating the canvas and initializing variables: * * ```js * function setup() { * // Code to run once at the start of the sketch. * } * ``` * * Code placed in `setup()` will run once before code placed in * <a href="#/p5/draw">draw()</a> begins looping. * If `setup()` is declared `async` (e.g. `async function setup()`), * execution pauses at each `await` until its promise resolves. * For example, `font = await loadFont(...)` waits for the font asset * to load because `loadFont()` function returns a promise, and the await * keyword means the program will wait for the promise to resolve. * This ensures that all assets are fully loaded before the sketch continues. * * * loading assets. * * Note: `setup()` doesn’t have to be declared, but it’s common practice to do so. * * @method setup * @for p5 * @return {void|Promise<void>} * * @example * function setup() { * createCanvas(100, 100); * * background(200); * * // Draw the circle. * circle(50, 50, 40); * * describe('A white circle on a gray background.'); * } * * @example * function setup() { * createCanvas(100, 100); * * // Paint the background once. * background(200); * * describe( * 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.' * ); * } * * function draw() { * // Draw circles repeatedly. * circle(mouseX, mouseY, 40); * } * * @example * let img; * * async function setup() { * img = await loadImage('assets/bricks.jpg'); * * createCanvas(100, 100); * * // Draw the image. * image(img, 0, 0); * * describe( * 'A white circle on a brick wall. The circle follows the mouse as the user moves, leaving a trail.' * ); * } * * function draw() { * // Style the circle. * noStroke(); * * // Draw the circle. * circle(mouseX, mouseY, 10); * } */ /** * A function that's called repeatedly while the sketch runs. * * Declaring the function `draw()` sets a code block to run repeatedly * once the sketch starts. It’s used to create animations and respond to * user inputs: * * ```js * function draw() { * // Code to run repeatedly. * } * ``` * * This is often called the "draw loop" because p5.js calls the code in * `draw()` in a loop behind the scenes. By default, `draw()` tries to run * 60 times per second. The actual rate depends on many factors. The * drawing rate, called the "frame rate", can be controlled by calling * <a href="#/p5/frameRate">frameRate()</a>. The number of times `draw()` * has run is stored in the system variable * <a href="#/p5/frameCount">frameCount()</a>. * * Code placed within `draw()` begins looping after * <a href="#/p5/setup">setup()</a> runs. `draw()` will run until the user * closes the sketch. `draw()` can be stopped by calling the * <a href="#/p5/noLoop">noLoop()</a> function. `draw()` can be resumed by * calling the <a href="#/p5/loop">loop()</a> function. * * @method draw * @for p5 * * @example * function setup() { * createCanvas(100, 100); * * // Paint the background once. * background(200); * * describe( * 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.' * ); * } * * function draw() { * // Draw circles repeatedly. * circle(mouseX, mouseY, 40); * } * * @example * function setup() { * createCanvas(100, 100); * * describe( * 'A white circle on a gray background. The circle follows the mouse as the user moves.' * ); * } * * function draw() { * // Paint the background repeatedly. * background(200); * * // Draw circles repeatedly. * circle(mouseX, mouseY, 40); * } * * @example * // Double-click the canvas to change the circle's color. * * function setup() { * createCanvas(100, 100); * * describe( * 'A white circle on a gray background. The circle follows the mouse as the user moves. The circle changes color to pink when the user double-clicks.' * ); * } * * function draw() { * // Paint the background repeatedly. * background(200); * * // Draw circles repeatedly. * circle(mouseX, mouseY, 40); * } * * // Change the fill color when the user double-clicks. * function doubleClicked() { * fill('deeppink'); * } */ /** * Turns off the parts of the Friendly Error System (FES) that impact performance. * * The <a href="https://github.com/processing/p5.js/blob/main/contributor_docs/friendly_error_system.md" target="_blank">FES</a> * can cause sketches to draw slowly because it does extra work behind the * scenes. For example, the FES checks the arguments passed to functions, * which takes time to process. Disabling the FES can significantly improve * performance by turning off these checks. * * @static * @property {Boolean} disableFriendlyErrors * * @example * // Disable the FES. * p5.disableFriendlyErrors = true; * * function setup() { * createCanvas(100, 100); * * background(200); * * // The circle() function requires three arguments. The * // next line would normally display a friendly error that * // points this out. Instead, nothing happens and it fails * // silently. * circle(50, 50); * * describe('A gray square.'); * } */ /** * Loads a p5.js library. * * A library is a function that adds functionality to p5.js by adding methods * and properties for sketches to use, or for automatically running code at * different stages of the p5.js lifecycle. Take a look at the * <a href="/contribute/creating_libraries/">contributor docs for creating libraries</a> * to learn more about creating libraries. * * @static * @method registerAddon * @param {Function} library The library function to register * * @example * function myAddon(p5, fn, lifecycles) { * fn.sayHello = function() { * this.textAlign(this.CENTER, this.CENTER); * this.text('Hello!', this.width / 2, this.height / 2); * }; * } * p5.registerAddon(myAddon); * * function setup() { * createCanvas(100, 100); * * background(200); * sayHello(); // The sayHello method is now available! * * describe('The text "Hello!"'); * } */ //#endregion export { Renderer2D as n, renderer2D as r, p5 as t };