Skip to content

Commit 5357b21

Browse files
authored
Merge pull request #8558 from imrinahru/pixelDensity-bug-fix-2x-new
fix: createGraphics inherits pixelDensity from parent sketch.
2 parents 369377d + 0682e87 commit 5357b21

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

src/core/p5.Renderer.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,14 @@ class Renderer {
7272
this._pInst = pInst;
7373
this._isMainCanvas = isMainCanvas;
7474
this.pixels = [];
75-
this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1;
75+
76+
if (isMainCanvas) {
77+
this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1;
78+
} else {
79+
80+
const parentDensity = pInst._pInst?._renderer?._pixelDensity;
81+
this._pixelDensity = parentDensity || Math.ceil(window.devicePixelRatio) || 1;
82+
}
7683

7784
this.width = w;
7885
this.height = h;

test/unit/core/rendering.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,4 +285,40 @@ suite('Rendering', function() {
285285
assert.deepEqual(pixelFromGfx, pixelFromImg);
286286
});
287287
});
288+
289+
suite('p5.prototype.createGraphics pixelDensity', function() {
290+
let myp5;
291+
292+
beforeEach(function() {
293+
myp5 = new p5(function(p) {
294+
p.setup = function() {
295+
p.createCanvas(100, 100);
296+
};
297+
});
298+
});
299+
300+
afterEach(function() {
301+
myp5.remove();
302+
});
303+
304+
test('createGraphics should inherit pixelDensity from parent sketch', function() {
305+
myp5.pixelDensity(1);
306+
const g = myp5.createGraphics(100, 100);
307+
assert.equal(g.pixelDensity(), 1);
308+
});
309+
310+
test('createGraphics should inherit non-default pixelDensity', function() {
311+
myp5.pixelDensity(3);
312+
const g = myp5.createGraphics(100, 100);
313+
assert.equal(g.pixelDensity(), 3);
314+
});
315+
316+
test('createGraphics should use default pixelDensity when not explicitly set', function() {
317+
// When no pixelDensity is set, both should match
318+
const expectedDensity = myp5.pixelDensity();
319+
const g = myp5.createGraphics(100, 100);
320+
assert.equal(g.pixelDensity(), expectedDensity);
321+
});
322+
});
323+
288324
});

0 commit comments

Comments
 (0)