gpt4 book ai didi

javascript - p5.j​​s && ecmascript6 表示法

转载 作者:行者123 更新时间:2023-12-03 04:41:13 27 4
gpt4 key购买 nike

我想在具有 ECMAScript 表示法的类中使用 p5.js 函数。

如何修复此代码?

class Sketch {
constructor(p, params) {
// generate vars use in class with object
if (typeof params !== 'undefined') {
for (let key in params) this[key] = params[key];
}
// p5.js object
this.p = p;
}
// p5.js setup method
setup() {
this.p.createCanvas();
}
// p5.js draw method
draw() {
}
}
sketch = new Sketch(p5,{});

错误:

this.p.createCanvas is not a function

最佳答案

The docs假设您必须实例化 p5 并传递在 p 上创建方法的初始化函数:

const myp5 = new p5(p => {
p.setup = () => {
p.createCanvas();
};

});

另请参阅Global and instance mode教程。

然而,这是一个非常奇怪的结构。虽然没有记录,但在 ES6 中应该可以子类化 p5:

class Sketch extends p5 {
constructor(params) {
super(p => {
// do any setup in here that needs to happen before the sketch starts
// (e.g. create event handlers)
// `p` refers to the instance that becomes `this` after the super() call
// so for example
if (typeof params == 'object' && params != null)
for (let key in params)
p[key] = params[key];
});

// `this` itself is the p5.js object
}
// p5.js setup method
setup() {
this.createCanvas();
}
// p5.js draw method
draw() {
}
}
const myp5 = new Sketch({});

请注意,p5 构造函数将调用您的方法;您不必自己执行myp5.setup()

关于javascript - p5.j​​s && ecmascript6 表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com