[英]incorporating p5.js in a Next.js (React App) website
I have a react app that runs perfectly on the local host. 我有一个在本地主机上运行完美的反应应用程序。 But when i add it to my Next.js (React.js) website, it says "ReferenceError: window is not defined."
但是,当我将它添加到我的Next.js(React.js)网站时,它说“ReferenceError:window is not defined。” I think this is because i am running P5.js on Node.js but it can only run on the browser.
我想这是因为我在Node.js上运行P5.js但它只能在浏览器上运行。 How can i fix this?
我怎样才能解决这个问题?
My P5.js sketch in a React App 我的P5.js在React应用程序中草绘
import React, { Component } from 'react';
// import logo from './logo.svg';
import p5 from 'p5';
class Sketch extends Component {
constructor(){
super()
this.renderRef = React.createRef()
this.state = {
x: 100,
y: 100
}
}
componentDidMount(){
this.sketch = new p5( p => {
p.setup = () => {
p.createCanvas(p.windowWidth, p.windowHeight)
.parent(this.renderRef.current);
p.background('white');
p.strokeWeight(5);
}
p.windowResized = () => {
p.resizeCanvas(p.windowWidth, p.windowHeight )
}
p.draw = () => {
if(p.mouseIsPressed){
p.stroke(225)
} else{
p.stroke(0, 0, 0);
}
p.line(p.mouseX , p.mouseY, p.mouseX , p.mouseY);
p.line(p.mouseX, p.mouseY , p.mouseX, p.mouseY);
}
});
}
render(){
return (
<div className="App">
<div ref={this.renderRef}></div>
</div>
);
}
}
export default Sketch;
Import p5 inside of componentDidMount
在
componentDidMount
导入p5
componentDidMount(){
const p5 = require("p5")
this.sketch = new p5( p => {
...
In NextJS, componentDidMount() is executed only the client where window and other browser specific APIs will be available. 在NextJS中,componentDidMount()仅执行窗口和其他特定于浏览器的API可用的客户端。 Have a look to this answer
看看这个答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.