javascript - p5js 在主范围内使用循环函数
问题描述
所以我在 p5js 中有这个非常基本的例子:
var e = 1;
function setup() {
window.canvas = createCanvas(200, 200);
}
function draw() {
fill(255, 255, 0);
ellipse(50 + e, 50, 30);
e++;
noLoop();
}
如果我们暂时忽略noLoop()
,这段代码只是复制一个圆圈并将其向右移动。
现在,我试图通过添加以下内容来控制正在播放的帧数:
function makeOneMove() {
loop();
}
因此,每当我makeOneMove()
像在脚本中那样调用时,我都希望它播放一帧。
但是,遗憾的是我收到了这个错误:
未捕获的 ReferenceError:未定义循环
所以我的问题是,我怎样才能使用它loop()
或noLoop()
只在 p5 的函数(如 setup 或 draw)中工作的函数。
解决方案
要逐帧执行此操作,您需要确保loop()
在您的setup()
方法中使用它,如下所示:
var e = 1;
function setup() {
createCanvas(200, 200);
makeOneMove(); // call makeOneMove in `setup`
}
function makeOneMove() {
loop();
}
function draw() {
background(255); // used to remove the "trail" of circles (remove if trail is wanted)
fill(255, 255, 0);
ellipse(50 + e, 50, 30);
e++;
noLoop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
您可以控制outside of和 inside of的值,而不是控制何时draw()
被调用。这样,就像被一遍又一遍地重复调用一样,它将采用 的新值并在该新偏移位置绘制圆。出于演示目的,我添加了一个在您单击时将调用的方法:e
draw()
makeOneMove()
draw()
e
mouseClicked()
makeOneMove()
var e = 1;
function setup() {
createCanvas(200, 200);
}
function makeOneMove() {
e++;
}
function draw() {
background(255); // used to remove the "trail" of circles (remove if trail is wanted)
fill(255, 255, 0);
ellipse(50 + e, 50, 30);
}
function mouseClicked() {
makeOneMove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
对于多个圆圈/对象,这取决于您如何表示数据/对象。最好的方法是使用对象(例如通过创建一个Class
),并更改每个对象的偏移量(即:e
值):
class Circle {
constructor(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.offset = 1; // (circles own `e` value)
}
}
var objects;
function setup() {
createCanvas(200, 200);
objects = [ // store all your onscreen objects in an array
new Circle(50, 50, 30, color(255, 255, 0)), // original object you had
new Circle(50, 100, 50, color(0, 255, 0))
];
}
function makeOneMove(objectIndex) {
objects[objectIndex].offset++;
}
function draw() {
background(255); // used to remove the "trail" of circles (remove if trail is wanted)
for(const circle of objects) {// loop through all objects in your `objects` array
// Draw the given object/circle
fill(circle.color);
ellipse(circle.x + circle.offset, circle.y, circle.r);
}
}
function mouseClicked() {
makeOneMove(0); // make object 0 in array move (for demo)
}
function keyPressed() {
makeOneMove(1); // make object 1 in array move (for demo)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
推荐阅读
- angular - 如何将搜索数据绑定到角度表
- algorithm - 用FFT求解n位串的汉明距离?
- python - 如何通过 HDMI 将 Python 线图输出发送到另一台显示器?
- javascript - 通过 react 中的特定 id 启用和禁用 onClick() 功能
- visual-studio-code - 如何使“按位置排序”成为大纲视图中的默认选项?
- reactjs - 找不到模块“@babel/helper-regex”需要堆栈
- git - 使用漂亮格式时如何为合并提交着色?
- javascript - 未提供查询参数时的默认 GraphQL 服务器字符串响应?
- c# - ASP.NET:如何避免动态创建按钮事件刷新页面而不是做相关代码的情况
- time-complexity - O(n) 和 O(log n) 的乘积是多少?