本文介绍了p5.j​​s&&ecmascript6表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want use p5.js function inside a class with ECMAScript notation.

如何修复此代码?

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,{});

错误:

推荐答案

文档说,您必须实例化 p5 并传递在 p 上创建方法的初始化程序函数:

The docs say that you must instantiate p5 and pass your initialiser function that creates the method on p:

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

另请参见全局和实例模式教程.

但是,这确实是一个很奇怪的构造.尽管未记录,但在ES6中应该可以将 p5 子类化:

This is a really weird construction however. Although it's not documented, in ES6 it should be possible to subclass 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().

Notice that the p5 constructor will invoke your methods; you don't have to do myp5.setup() yourself.

这篇关于p5.j​​s&&ecmascript6表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 13:56