我希望在具有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不是函数
答案 0 :(得分:1)
The docs说您必须实例化 p5
并传递您在p
创建方法的初始化函数:
const myp5 = new p5(p => {
p.setup = () => {
p.createCanvas();
};
…
});
然而,这是一个非常奇怪的结构。虽然没有记录,但在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()
。
答案 1 :(得分:0)
摆弄这个问题。我能够像这样实现p5的继承:
import p5 from 'p5';
const MIN_RAD = 150;
const MAX_RAD = 250;
const ITEM_COLOR = 'red';
const BG = 'rgba(50,50,50,.05)';
const VELOCITY = 1;
export default class Sketch extends p5 {
constructor(sketch = ()=>{}, node = false, sync = false) {
super(sketch, node, sync);
console.log('Sketch [this:%o]', this);
this.setup = this.setup.bind(this);
this.draw = this.draw.bind(this);
this.render = this.render.bind(this);
this.increment = this.increment.bind(this);
this.windowResized = this.windowResized.bind(this);
}
setup() {
console.log('setup', this.windowWidth, this.windowHeight);
this.createCanvas(this.windowWidth, this.windowHeight, p5.WEBGL);
this.bg = this.color(BG);
this.itemColor = this.color(ITEM_COLOR);
this.rad = MIN_RAD;
this.grow = true;
this.frame = 0;
}
draw() {
this.increment();
this.render();
}
render() {
let x = this.windowWidth / 2;
let y = this.windowHeight / 2;
this.background(this.bg);
this.fill(this.itemColor);
this.stroke(this.itemColor);
this.ellipse(x, y, this.rad, this.rad);
}
increment() {
this.rad = this.grow ? this.rad + VELOCITY : this.rad - VELOCITY;
if (this.rad > MAX_RAD) {
this.grow = false;
};
if (this.rad < MIN_RAD) {
this.grow = true;
}
this.frame++;
}
// EVENTS
windowResized() {
console.log('windowResized', this.windowWidth, this.windowHeight);
this.resizeCanvas(this.windowWidth, this.windowHeight);
}
}
此类可以正常导入,并通过调用构造函数进行实例化。
import Sketch from './sketch';
...
const sketch = new Sketch();
稍微深入挖掘源代码,有两个关键状态可以自动神奇地激活所谓的全局&#39;模式,其中p5将其内容转储到window
(要避免)。
draw
setup
和window
sketch
参数为falsey p5/Core
使用这些条件设置其内部_isGlobal
道具,用于将上下文定义为window
或this
,并在整个过程中有条件地对此进行操作。 EG:core.js#L271
只是扩展选定的答案(这是正确的,除了我在空对象中传递错误)。
坦率地说,两种记录的构造方法都不令人满意。这是一项改进,但我们仍需要做额外的工作来管理范围。