简体   繁体   English

为什么此代码在 p5.js 中的 canvas 上没有任何内容?

[英]Why does this code not output anything onto the canvas in p5.js?

In p5.js I'm trying to visualise a Linear Search Algorithm.在 p5.js 中,我试图可视化线性搜索算法。 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.当我将 forEach 循环放入设置 function 时,什么也没有出现。 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)如果我把它放在draw function中,我看到我正在寻找的确切结果弹出半秒钟然后消失...... (程序运行时调用设置function,并且不断调用绘图循环每帧)(function 线从第一个 x,y 到第二个 x,y 线(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程序运行时调用setup function,每帧不断调用draw loop

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.因此,使用您拥有的代码, setup function 在程序的最开始运行一次,然后draw function 每秒调用 60 次。 The only thing you're doing inside the draw function is drawing a background, which removes what you drew in the setup function.您在draw function 中所做的唯一一件事就是绘制背景,这会删除您在setup function 中绘制的内容。 Try removing the call to background(255) to see what I mean.尝试删除对background(255)的调用以了解我的意思。

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?然后当你把你的代码移到draw function中时,我会提供这个提示:每帧buffer变量的值是多少? You might use some console.log() statements to answer that.您可能会使用一些console.log()语句来回答这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM