Infinity
Infinity

Reputation: 73

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.

Upvotes: 7

Views: 6616

Answers (2)

ggorlen
ggorlen

Reputation: 56885

The loop()/noLoop() approach is a good option, but I don't see a problem with skipping draw() entirely:

let x = 10;
let y;
let x2 = 190;
let y2;

function setup() {
  createCanvas(200, 200);
  renderLine();
}

function mousePressed() {
  renderLine();
}

function keyPressed() {
  renderLine();
}

function renderLine() {
  clear();
  y = floor(random(201));
  y2 = 200 - floor(random(201));
  line(10, y, 190, y2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

... or calling draw once with noLoop() enabled (to separate it from setup() code), then using key or mouse handlers the rest of the way to call redraw() which runs draw() one time:

let x = 10;
let y;
let x2 = 190;
let y2;

function setup() {
  createCanvas(200, 200);
  noLoop();
}

function draw() {
  clear();
  y = floor(random(201));
  y2 = 200 - floor(random(201));
  line(10, y, 190, y2);
}

function mousePressed() {
  redraw();
}

function keyPressed() {
  redraw();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

Program flow from the p5 docs might be helpful for exploring these options.

As a minor aside, since you've imported p5, I'd just use the floor and random functions they provide.

Upvotes: 1

Kevin Workman
Kevin Workman

Reputation: 42176

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.

Upvotes: 6

Related Questions