Created
October 2, 2018 12:30
-
-
Save WoonHaKim/0911c925701f188d1c1f78e32e35d478 to your computer and use it in GitHub Desktop.
Connecting p5js and React js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uses dynamic component loading feature of nextjs | |
import dynamic from 'next/dynamic'; | |
import sketch from './BGSketch'; // Sketch to load dynamically | |
import css from '../styles.less' | |
const P5DynamicLoader = dynamic(import('./P5Wrapper'), { | |
ssr: false, | |
loading: () => <div className={css.backgroundCanvas}>Loading Background...</div>, | |
}); | |
export default () => <div className={css.backgroundCanvas}><P5DynamicLoader sketch = {sketch}/></div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//requires p5 library from npm | |
import React, { Component } from 'react'; | |
import p5 from 'p5'; | |
export default class P5Wrapper extends React.Component { | |
componentDidMount() { | |
this.canvas = new p5(this.props.sketch, this.wrapper); | |
if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) { | |
this.canvas.myCustomRedrawAccordingToNewPropsHandler(this.props) | |
} | |
} | |
componentWillReceiveProps(newprops) { | |
if(this.props.sketch !== newprops.sketch){ | |
this.canvas.remove() | |
this.canvas = new p5(newprops.sketch, this.wrapper) | |
} | |
if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) { | |
this.canvas.myCustomRedrawAccordingToNewPropsHandler(newprops) | |
} | |
} | |
componentWillUnmount() { | |
this.canvas.remove() | |
} | |
render() { | |
return <div ref={wrapper => this.wrapper = wrapper}></div> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment