Search code examples
javascriptperformanceanimationp5.jsframe-rate

p5.js sketch very slow on mobile devices


I'm building a creative simulation in p5.js by employing double pendula. Here is the link to the stripped-down version of the code (I'm not sure it can be made smaller): https://github.com/amzon-ex/amzon-ex.github.io/tree/master/dp-sketch-stripped

Here is where you can see the animation: https://amzon-ex.github.io/dp-sketch-stripped/dp-sketch.html

When I run this on my laptop (Windows 10, MS Edge 88) I get about 55-60 fps, which is what I want. However, when I run the same sketch on a mobile device (Android, Chrome 88) the performance is very poor and I hardly get 5-6 fps. I do not understand what is complicated about my code that contributes to such a poor performance. I have ran other kinds of p5.js sketches before on mobile and they've worked well.

Any insight is appreciated.

Since I have a few files in the project link I provided, here's a quick guide (there is absolutely no need to read everything):

  1. sketch.js is the key file, which builds the animation. It takes an image, builds an array filled with brightness values from the image (array lumamap, in setup()). Then I draw trails for my pendula where the brightness of the trail at any pixel corresponds to the brightness value in lumamap.
  2. dp-sketch.html is the HTML container for the p5 sketch.
  3. libs/classydp.js houses the DoublePendulum class which describes a double pendulum object.

Solution

  • As I've found out with some help, the issue is tied to varying pixel density on different devices. As mobile devices have higher pixel density compared to desktops/laptops, my 500x500 canvas becomes much bigger on those displays, hence leading to many more pixels to render. Coupled with the fact that mobile processors are weaker in comparison to desktop processors, the lag/low framerate is expected.

    This can be avoided by setting pixelDensity(1) in setup(); which avoids rendering larger canvases on dense-pixel devices.