Can i make my p5.js draw() function run only once, and then only on a button click?
I have this snippet of p5.js code:
let x = 10;
let y = Math.floor(Math.random()*201);
let x2 = 190;
let y2 = 200 - Math.floor(Math.random()*201);
function setup() {
createCanvas(200, 200);
}
function draw() {
clear();
y = Math.floor(Math.random()*201);
y2 = 200 - Math.floor(Math.random()*201);
line(10, y, 190, y2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
and I want to make it so that it runs once automatically, then again every time a button is pressed.
My main concern here is the "run only once" bit, so if anyone can help me out with that, it'd be great.
Thanks in advance! :)
Solution 1:
Rabbid76's answer is already correct, but just in case you're curious: you can also use the noLoop()
and loop()
functions to control whether draw()
is continuously called.
Here's an example:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
noLoop();
}
function mousePressed() {
ellipse(mouseX, mouseY, 25, 25);
}
function keyPressed() {
loop();
}
This code calls the noLoop()
function to tell p5.js not to call the draw()
function continuously. This allows you to draw circles with the mouse, without them being cleared by the background. Then when a key is pressed, this code calls the loop()
function to start calling draw()
again. This draws a background, and then stops calling the draw()
function continuously again.
You can find more info in the reference.