初学者关于p5js print() 函数的问题
我在 GitHub 上看到了一些已关闭的帖子,以及关于随机返回的偶尔未解决的类似问题,但我可以得到一个很好的解释,解释为什么在定义对象的简单 print()
命令上该对象是似乎在循环中打印在控制台上:
我刚刚开始使用 p5js,并且不了解 javascript。所以它可能是命令放置的地方(function setup()
或 function draw()
),我仍然不确定为什么它们默认出现在编辑器起始页上,否则我需要指定我希望结果只打印一次(?)。
I have seen some closed posts on GitHub, and the occasional unsolved similar question on random returns, but I can get a good explanation as to why on a simple print()
command of a defined object the object is being printed on the console seemingly in a loop:
I just started using p5js, and don't know javascript. So it may be where the commands are placed (function setup()
or function draw()
), which I am still unsure why they are defaulted on the editor start page, or else I need to specify that I want the result printed just once (?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为
draw()
在循环上运行。在幕后, p5js 库正在使用requestAnimationFrame
调用绘制()
。您可以将
print
语句移至setup()
函数内,该函数仅在脚本开始时运行一次。或者,如果您愿意,可以设置条件打印块,如下所示:
注意:还可以考虑使用
p5.Vector
对象用于更清晰的输出。如果您需要从
draw()
函数中调用的函数获取输出,您可以应用相同的原则,如下所示:可运行示例:
This happens because
draw()
runs on a loop. Behind the scenes, the p5js library is usingrequestAnimationFrame
to calldraw()
.You could move the
print
statement to be within thesetup()
function, which only runs once at the start of the script.Or if you prefer, you can set up a conditional print block as follows:
Note: also consider using the
toString
method in thep5.Vector
object for cleaner output.If you need to get output from a function being called from within the
draw()
function, you can apply the same principles as follows:Runnable example: