I recently finished up a project where I used P5.js extensively. I am writing up several short blog posts on development issues, ideas and techniques that helped me out.

Here’s the second post…

Accounting for Pixel Density when using the Canvas tag.

Early on in the development phase of my last project I ran into an unsettling issue where none of my builds were rendering on iPhone 12 iOS browsers. Not Safari, not Firefox, Chrome, Focus, Brave, Opera… An old iPad, no problem, but no luck with any kind of recent device.

Other P5.js projects were showing up correctly so I knew the problem had to be with my specific project.

Turns out, pixel density was the root of the issue.

What I came to learn is that browsers have a built-in limit to the pixel dimensions of your canvas object in the browser. This makes sense, but I hadn’t run into this issue before.

After sorting out a different issue with Safari’s remote debugging tool, I found the error message, "Canvas area exceeds the maximum limit (width * height > 16777216)."

Initially I was very confused by this since my dimensions were:

let canvasW = 1613;
let canvasH = 1225;

And those dimensions only added up to 1,975,925 which while pretty big, was still no where near the limit.

Turns out, the pixel density ratio for the iPhone 12 and other recent devices is 3. This meant that my canvasW, and canvasH values were being tripled.

The fix for this was to use P5.js’ built-in pixelDensity method to both get and set the pixel density ratio. Here’s the code I used at the beginning of the P5.js setup() function before the createCanvas declaration was called.

if (p55.pixelDensity() > 2) p55.pixelDensity(2);

Is this a perfect solution?? No. Does it work?? Yes!

In general, be careful and test out how this work-around looks for your projects. Messing with pixel density ratios can have impacts on the visual clarity of your projects.

Good luck!