From 0682e87eb625c7f697119268addef3b070361629 Mon Sep 17 00:00:00 2001 From: imrinahru <120927437+imrinahru@users.noreply.github.com> Date: Mon, 23 Feb 2026 00:28:19 -0500 Subject: [PATCH] fix: createGraphics inherits pixelDensity from parent sketch. In p5.js ver.2x, createGraphics() used window.devicePixelRatio for the graphics buffer's pixel density, ignoring the parent sketch setting. This caused graphics buffer to render pixelDensity(2) on retina displays even when pixelDensity(1) was explicitly set. The fix makes graphics buffer renderers (isMainCanvas === false) inherit pixelDensity from the parent sketch via pInst._pInst._renderer instead of always using window.devicePixelRatio. --- src/core/p5.Renderer.js | 9 ++++++++- test/unit/core/rendering.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/core/p5.Renderer.js b/src/core/p5.Renderer.js index 04caa1144d..c0fe4a6c02 100644 --- a/src/core/p5.Renderer.js +++ b/src/core/p5.Renderer.js @@ -72,7 +72,14 @@ class Renderer { this._pInst = pInst; this._isMainCanvas = isMainCanvas; this.pixels = []; - this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; + + if (isMainCanvas) { + this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; + } else { + + const parentDensity = pInst._pInst?._renderer?._pixelDensity; + this._pixelDensity = parentDensity || Math.ceil(window.devicePixelRatio) || 1; + } this.width = w; this.height = h; diff --git a/test/unit/core/rendering.js b/test/unit/core/rendering.js index c75039a990..7ffd6babf7 100644 --- a/test/unit/core/rendering.js +++ b/test/unit/core/rendering.js @@ -285,4 +285,40 @@ suite('Rendering', function() { assert.deepEqual(pixelFromGfx, pixelFromImg); }); }); + + suite('p5.prototype.createGraphics pixelDensity', function() { + let myp5; + + beforeEach(function() { + myp5 = new p5(function(p) { + p.setup = function() { + p.createCanvas(100, 100); + }; + }); + }); + + afterEach(function() { + myp5.remove(); + }); + + test('createGraphics should inherit pixelDensity from parent sketch', function() { + myp5.pixelDensity(1); + const g = myp5.createGraphics(100, 100); + assert.equal(g.pixelDensity(), 1); + }); + + test('createGraphics should inherit non-default pixelDensity', function() { + myp5.pixelDensity(3); + const g = myp5.createGraphics(100, 100); + assert.equal(g.pixelDensity(), 3); + }); + + test('createGraphics should use default pixelDensity when not explicitly set', function() { + // When no pixelDensity is set, both should match + const expectedDensity = myp5.pixelDensity(); + const g = myp5.createGraphics(100, 100); + assert.equal(g.pixelDensity(), expectedDensity); + }); + }); + });