Possibility to avoid redraw with virtual mouse cursor

I am developing a little game with p5.js in which I need to draw my own mouse cursor (for reasons that are not so important). Apart from the mouse cursor, the game has mostly static content and each frame consist of around 1-5 elements (images, basic shapes, text). At the moment, each frame is constantly redrawn.

I realized that the game is pretty CPU heavy, especially in Firefox. I already found out that this becomes (in my case) not better, when I use createGraphics() to create screens already during setup. The problem is not the creation of content, but the constant redrawing.

As far as my understanding goes (I’m very new to p5.js), when using a virtual mouse cursor as in my case, I have no choice to avoid constant redrawing, right? The virtual mouse cursor can be anywhere on the screen, can occlude any element and its position should be constantly updated. Or is there any trick I could pull?

edit: not sure if this is relevant, but the virtual mouse cursor uses requestPointerLock() and is moved according to movedX/movedY

Hello @monade,

It’s up to you how often to draw the cursor, but most naturally is to do it once every time draw is called. Default is 60 times per second on most computers, but you can change that using the frameRate() function.

Redrawing the virtual mouse pointer every frame is reasonable and shouldn’t be heavy on the CPU/GPU. Are you experiencing slowdowns that you think is caused by the mouse drawing routine?

Thanks for your quick reply! I indeed want to redraw the cursor every frame draw() is called.

I now realized that I get the heavy CPU (at least with firefox) already when simply having background(50) in the draw routine. What matter is mostly not what is drawn, but that anything is drawn. With background(50) being called every cycle of draw(), Firefox is at around 65% CPU load and Chrome around 15%. If I remove the call to background(50), CPU is not noticable for both browsers. This is on a resonably fast computer (Thinkpad T480s), operating system Linux/Ubuntu and fairly recent stable versions of both browsers.

When you say “redrawing the virtual mouse pointer” you mean redrawing the whole canvas? This was part of my question: whether I can avoid redrawing the other elements, when redrawing the virtual mouse cursor. If I just draw the new mouse cursor on top of the previous draw, the mouse at its old position would also be present.

If you host a version online, using https://editor.p5js.org or similar, I can run it on my laptop (Macbook Air) and see if I experience the same thing.

What I tried to get across is that it is not likely that the portion of code responsible for redrawing the mouse is especially resource hungry. That it’s probably not the reason, your code is running slow. You could avoid redrawing the other elements by drawing them once to an off-screen graphics buffer. Look up createGraphics.

1 Like