Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

p5.js how to freeze canvas?

I try to do something like that :

function setup() {
  createCanvas(500, 250);
  //frameRate(1);
}

function draw() {
  background(50, 50, 150);
  
  translate(10, 10);
  for (let i = 0; i < 30; i++) {
    rect(i*15, 0, 10, random(30, 120));
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

But i want to "freeze" this canvas, so if i load the page i will have 30 rect() at a random height between 30 and 120.

like image 569
Anatole Lucet Avatar asked Oct 15 '25 03:10

Anatole Lucet


2 Answers

One option would be to use noLoop() method inside setup function that will stop draw method loop.

function setup() {
  createCanvas(500, 250);
  noLoop()
}

function draw() {
  background(50, 50, 150);

  translate(10, 10);
  for (let i = 0; i < 30; i++) {
    rect(i * 15, 0, 10, random(30, 120));
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

Note that with using noLoop and loop methods, you can toggle draw loop on some event for example mousePressed like this.

let stop = true;

function setup() {
  const canvas = createCanvas(500, 250);
  if(stop) noLoop();
  canvas.mousePressed(function() {
    stop = !stop;
    stop ? noLoop() : loop()
  })
}

function draw() {
  background(50, 50, 150);

  translate(10, 10);
  for (let i = 0; i < 30; i++) {
    rect(i * 15, 0, 10, random(30, 120));
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

Other option is to create bars array once in setup function and then show them with draw method. This way you don't have to stop draw loop.

const bars = []
class Bar {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
  }
  show() {
    rect(this.x, this.y, this.w, this.h);
  }
}

function setup() {
  createCanvas(500, 250);
  for (let i = 0; i < 30; i++) {
    bars.push(new Bar(i * 15, 0, 10, random(30, 120)))
  }
}

function draw() {
  background(50, 50, 150);
  translate(10, 10);
  bars.forEach(bar => bar.show())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
like image 188
Nenad Vracar Avatar answered Oct 16 '25 16:10

Nenad Vracar


Since i was looking for a way to simply freeze the canvas and this post was the first that came up i thought i leave the solution here.

you could use this with an extra incrementor for the number of rectangles which then triggers noLoop()

From the p5 docs

freezing the canvas by holding down any mouse button

function mousePressed() {
  noLoop();
}

function mouseReleased() {
  loop();
}
like image 33
dinoDonga Avatar answered Oct 16 '25 16:10

dinoDonga