在 React 项目中使用 p5 库

Using p5 library inside react project

我正在尝试将 p5 库与 React 结合使用。一切正常,除了我不能使用一些 p5s 函数,如:keyPressed()、keyReleased()。而 mouseClicked() 和 mousePressed() 等函数工作得很好。

const setup = (p5, canvasParentRef) => {
        // use parent to render the canvas in this ref
        // (without that p5 will render the canvas outside of your component)
        console.log(props.test)
        const cnv = p5.createCanvas(500, 500).parent(canvasParentRef);
        plr = new Player(p5.width / 2, p5.height / 2);
        food = new Food(p5);

        cnv.mouseClicked((event) => {
            console.log(event);
        })
        cnv.keyReleased((event) => {
            console.log(event);
        });
    };

这就是代码的样子。 mouseClicked 没有给出错误,而 keyReleased 和其他与键盘输入相关的函数给出错误提示 TypeError: cnv.keyReleased is not a function

像普通的 p5 实例模式一样,您定义函数。看起来您正在尝试执行一些操作,例如添加事件侦听器。

https://p5js.org/examples/instance-mode-instantiation.html

此外,还有一些拼写错误

const setup = (p5, canvasParentRef) => {
        // use parent to render the canvas in this ref
        // (without that p5 will render the canvas outside of your component)
        console.log(props.test)
        const cnv = p5.createCanvas(500, 500).parent(canvasParentRef);
        plr = new Player(p5.width / 2, p5.height / 2);
        food = new Food(p5);

        cnv.mouseIsClicked = (event) => {
            console.log(event);
        }
        cnv.keyReleased = (event) => {
            console.log(event);
        };
    };