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); + }); + }); + });