I’m trying to have a few circles drawn on the screen that do not move after initialization. Right now it is constantly drawing them to the screen instead of keeping them there. Here’s the code:
JavaScript
x
11
11
1
for (let i = 0; i < 1; i++) {
2
//location
3
const r = random(100, 900);
4
const r2 = random(900, 100);
5
//size
6
const rS = random(50, 250);
7
const rS2 = random(250, 50);
8
//draw the ellipse with parameters
9
ellipse(r, r2, rS, rS2);
10
}
11
(This is with the p5.js library)
Advertisement
Answer
It sounds like your code is in the draw()
function, which is called multiple times a second. Since you call random()
every single time, it creates new parameters every single time. Instead, you should assign parameters to a variable somewhere else (like in the setup
function) and then use those in the draw function. Something like:
JavaScript
1
22
22
1
var ellipses = [];
2
3
function setup() {
4
createCanvas(640, 480);
5
for (let i = 0; i < 1; i++) {
6
ellipses.push({
7
r: random(100, 300),
8
r2: random(300, 100),
9
rS: random(50, 250),
10
rS2: random(250, 50)
11
});
12
}
13
}
14
15
function draw() {
16
clear();
17
//location
18
//draw the ellipse with parameters
19
ellipses.forEach(function (e) {
20
ellipse(e.r, e.r2, e.rS, e.rS2);
21
})
22
}
JavaScript
1
1
1
<script src="https://unpkg.com/p5@1.1.9/lib/p5.min.js"></script>