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.
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>
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With