fix: createGraphics inherits pixelDensity from parent sketch. by imrinahru · Pull Request #8558 · processing/p5.js
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.
Resolves #8289
Changes:
createGraphics() now inherits the parent sketch's pixelDensity instead of always using window.devicePixelRatio.
Bug: When calling pixelDensity(1) on the main sketch, createGraphics() still created a buffer with the screen's native pixel density (e.g., 2 on Retina/HiDPI displays).
pixelDensity(1); let g = createGraphics(400, 400); console.log(g.pixelDensity()); // Expected: 1, Actual: 2
Cause: In the v2.0 refactoring, _pixelDensity was moved from the sketch to the Renderer constructor. For graphics buffers (isMainCanvas === false), the renderer always set:
this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1;
This ignores the parent sketch's pixelDensity setting entirely.
Fix: For graphics buffer renderers, inherit the pixel density from the parent sketch via pInst._pInst._renderer._pixelDensity, falling back to window.devicePixelRatio if unavailable.
Files changed:
src/core/p5.Renderer.js— Fixed the constructor to inherit pixelDensity for non-main-canvas rendererstest/unit/core/rendering.js— Added 3 unit tests for pixelDensity inheritance
Screenshots of the change:
Bug happened with code:
const sketch = function(p) { p.setup = function() { p.createCanvas(400, 400); p.pixelDensity(1); let g = p.createGraphics(400, 400); console.log("Canvas pixelDensity:", p.pixelDensity()); console.log("Graphics pixelDensity:", g.pixelDensity()); }; };
Additional notes:
There were 4 pre-existing failures in p5.Shader.js and typography.js, which looked unrelated from my fix.
PR Checklist
-
npm run lintpasses - Inline reference is included / updated
- Unit tests are included / updated


