Indeed it is so. But we can try to mitigate some of it.
If you have a sketch which just displays a static drawing you can call noLoop() to halt the sketch:
'use strict';
function setup() {
createCanvas(500, 400);
noLoop();
}
Or if you have a sketch which only needs to update the canvas after a user input such as moving the mouse, besides using noLoop() you also call redraw() within the user input event callback:
'use strict';
function setup() {
createCanvas(500, 400).mouseMoved(mouseMovedEvent);
noLoop();
}
function draw() {
background('#' + hex(~~random(0x1000), 3));
}
function mouseMovedEvent() {
redraw();
}
For a more general approach you can attach the noLoop() & loop() functions to the canvas onmouseout() & onmouseover() listeners:
'use strict';
function setup() {
createCanvas(500, 400);
noLoop();
canvas.onmouseout = () => this.noLoop();
canvas.onmouseover = () => this.loop();
}
function draw() {
background('#' + hex(~~random(0x1000), 3));
}
Check it out the example above running online on the link below:
BtW, I also made an instance mode for the “Mouse Loop Toggle Events” example sketch:
/**
* Mouse Loop Toggle Events (v1.0.0)
* GoToLoop (2021-Aug-21)
*
* Discourse.Processing.org/t/multiple-sketches-in-instance-mode/11222/4
* Bl.ocks.org/GoSubRoutine/ed99264642c99e34919e5a6921ec1760
*
* Bl.ocks.org/GoSubRoutine/raw/
* ed99264642c99e34919e5a6921ec1760/index.instance.html
*/
'use strict';
new p5(p => {
p.setup = function () {
p.createCanvas(500, 400)//.mouseMoved(mouseMovedEvent);
p.noLoop();
p.canvas.onmouseout = () => p.noLoop();
p.canvas.onmouseover = () => p.loop();
};
p.draw = function () {
p.background('#' + p.hex(~~p.random(0x1000), 3));
};
function mouseMovedEvent() {
p.redraw();
}
});