In p5.js I'm trying to visualise a Linear Search Algorithm. I have an array of numbers and want to visualise them by drawing them as lines pointing upwards.
When I put the forEach loop in the setup function, nothing appears. If I put it in draw function, I see the exact result that I'm looking for pop up for half a second and then dissapear... (The setup function is called when the program is run, and the draw loop is continuously called every frame) (The line function draws a line from the first x,y to the second x,y line(x,yx,y)
Here's the code:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let buffer = 0
function setup() {
createCanvas(400, 400);
numbers.forEach((number) => {
stroke(0);
strokeWeight(4);
line(buffer, height, buffer, number * 50)
buffer += 15
});
}
function draw() {
background(255);
}
Think about the order that things happen in.
You said it yourself:
The setup function is called when the program is run, and the draw loop is continuously called every frame
So with the code you have, the setup
function runs once at the very beginning of your program, and then the draw
function is called 60 times per second. The only thing you're doing inside the draw
function is drawing a background, which removes what you drew in the setup
function. Try removing the call to background(255)
to see what I mean.
Then when you move your code into the draw
function, I'll offer this hint: What is the value of the buffer
variable each frame? You might use some console.log()
statements to answer that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.