Skip to content
Advertisement

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement