I try to do something like that :
JavaScript
x
13
13
1
function setup() {
2
createCanvas(500, 250);
3
//frameRate(1);
4
}
5
6
function draw() {
7
background(50, 50, 150);
8
9
translate(10, 10);
10
for (let i = 0; i < 30; i++) {
11
rect(i*15, 0, 10, random(30, 120));
12
}
13
}
JavaScript
1
1
1
<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.
JavaScript
1
13
13
1
function setup() {
2
createCanvas(500, 250);
3
noLoop()
4
}
5
6
function draw() {
7
background(50, 50, 150);
8
9
translate(10, 10);
10
for (let i = 0; i < 30; i++) {
11
rect(i * 15, 0, 10, random(30, 120));
12
}
13
}
JavaScript
1
1
1
<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.
JavaScript
1
19
19
1
let stop = true;
2
3
function setup() {
4
const canvas = createCanvas(500, 250);
5
if(stop) noLoop();
6
canvas.mousePressed(function() {
7
stop = !stop;
8
stop ? noLoop() : loop()
9
})
10
}
11
12
function draw() {
13
background(50, 50, 150);
14
15
translate(10, 10);
16
for (let i = 0; i < 30; i++) {
17
rect(i * 15, 0, 10, random(30, 120));
18
}
19
}
JavaScript
1
1
1
<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.
JavaScript
1
25
25
1
const bars = []
2
class Bar {
3
constructor(x, y, w, h) {
4
this.x = x;
5
this.y = y;
6
this.w = w;
7
this.h = h;
8
}
9
show() {
10
rect(this.x, this.y, this.w, this.h);
11
}
12
}
13
14
function setup() {
15
createCanvas(500, 250);
16
for (let i = 0; i < 30; i++) {
17
bars.push(new Bar(i * 15, 0, 10, random(30, 120)))
18
}
19
}
20
21
function draw() {
22
background(50, 50, 150);
23
translate(10, 10);
24
bars.forEach(bar => bar.show())
25
}
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>