Issues with pixel resolutions using image() on a phone?


I’m attempting to use p5js to place a bunch of images in a grid like fashion on a canvas and have the user save the sketch to use as a background for their phone.

I get the users phone resolution using displayWidth, displayHeight and set it as my canvas.

I load the image into an img variable using loadImage() and then call the image function to draw my image onto the canvas.

However when I call the image function to draw the image and resize it for example
image(img, 0, 0, 300, 300) and download it to my phone, the canvas resolution says what’s expected - displayWidth, displayHeight, but the interesting thing is that the image enhanced at least 3x than what I specified in the image function.

I assume this has to do with pixelDensity so I tried calling the function before I call the image() but it didn’t work.

Can anyone explain to me why this happens?

Here is my code:

var img; 

function preload() {

	str = '';

	img = loadImage(str);

function setup() {
	cnv = createCanvas(displayWidth, displayHeight);

function draw() {
//	pixelDensity(1);
	image(img, 0, 0, 200, 200);
	saveCanvas('background', 'jpg')

Thank you!

1 Like

Hello @seang42,

It sounds to me like you already have this figured out, it happens because of the pixel scaling going on behind the scenes. The p5.js functions (like image) adjust for that.

image(img, 0, 0, 200, 200);

The above results in an image 200×200 pixels to be drawn. While the example below will result in a 600×600 pixel image.

image(img, 0, 0, 200, 200);

If you have a device with a pixel density of 3 and want to put 200×200 physical pixels on that canvas, you have to divide all your dimensions by 3. Or use scale() and displayDensity() to adjust all dimensions for you:

scale(1 / displayDensity());
image(img, 0, 0, 200, 200);
1 Like