我希望在类中使用p5.js函数,并使用ECMAScript表示法。
如何修正这段代码?
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不是一个函数
发布于 2017-03-28 21:50:59
医生们说您必须实例化p5并传递在p上创建方法的initialiser函数
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()。
发布于 2017-11-06 05:33:11
修补这个问题。我能够像这样实现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();稍微深入一下源代码,有两种关键状态可以自动神奇地激活所谓的“全局”模式,其中p5将其内核转储到window上(为了避免)。
draw和setup都存在于window上sketch参数是falsey的p5/Core使用这些条件来设置其内部_isGlobal支柱,用于将上下文定义为window或this,并在整个过程中对其进行有条件的操作。例:core.js#L271
只在选择的答案上展开(这是正确的,除非我得到一个空对象传递的错误)。
坦率地说,这两种记录在案的施工方法都不能令人满意。这是一个改进,但我们仍然需要做额外的工作来管理范围。
https://stackoverflow.com/questions/43079407
复制相似问题