diff --git a/src/core/p5.Renderer.js b/src/core/p5.Renderer.js index 8f51a5802f..c869f3e6b4 100644 --- a/src/core/p5.Renderer.js +++ b/src/core/p5.Renderer.js @@ -158,10 +158,11 @@ class Renderer extends p5.Element { // get(x,y,w,h) } - const region = new p5.Image(w, h); + const region = new p5.Image(w*pd, h*pd); + region._pixelDensity = pd; region.canvas .getContext('2d') - .drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w, h); + .drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w*pd, h*pd); return region; } diff --git a/src/image/p5.Image.js b/src/image/p5.Image.js index 36a5a162f8..9e45ffa510 100644 --- a/src/image/p5.Image.js +++ b/src/image/p5.Image.js @@ -220,6 +220,48 @@ p5.Image = class { this.pixels = []; } + /** + * Gets or sets the pixel density for high pixel density displays. By default, + * the density will be set to 1. + * + * Call this method with no arguments to get the default density, or pass + * in a number to set the density. If a non-positive number is provided, + * it defaults to 1. + * + * @method pixelDensity + * @param {Number} [density] A scaling factor for the number of pixels per + * side + * @returns {Number} The current density if called without arguments, or the instance for chaining if setting density. + */ + pixelDensity(density) { + if (typeof density !== 'undefined') { + // Setter: set the density and handle resize + if (density <= 0) { + const errorObj = { + type: 'INVALID_VALUE', + format: { types: ['Number'] }, + position: 1 + }; + + p5._friendlyParamError(errorObj, 'pixelDensity'); + + // Default to 1 in case of an invalid value + density = 1; + } + + this._pixelDensity = density; + + // Adjust canvas dimensions based on pixel density + this.width /= density; + this.height /= density; + + return this; // Return the image instance for chaining if needed + } else { + // Getter: return the default density + return this._pixelDensity; + } + } + /** * Helper function for animating GIF-based images with time */