live example: https://jsfiddle.net/pdb7kraL/
Last active
July 30, 2017 16:23
-
-
Save thomasboyt/bcc496c823a01ac5f648 to your computer and use it in GitHub Desktop.
immediate-mode canvas rendering with react
This file contains 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
const CanvasComponent = React.createClass({ | |
propTypes: { | |
render: React.PropTypes.func.isRequired, | |
}, | |
componentDidMount() { | |
this._canvas = ReactDOM.findDOMNode(this); | |
this._ctx = this._canvas.getContext('2d'); | |
this.renderCanvas(); | |
}, | |
componentDidUpdate() { | |
this.renderCanvas(); | |
}, | |
renderCanvas() { | |
this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); | |
this.props.render(this._ctx, this.props); | |
}, | |
render() { | |
return <canvas />; | |
}, | |
}); | |
// Usage | |
function renderCanvas(ctx, {time}) { | |
ctx.font = "12px sans-serif"; | |
ctx.fillText("Hello from <canvas />!", 10, 20); | |
ctx.fillText("The time is:", 10, 50); | |
ctx.fillText(time, 10, 65); | |
} | |
const App = React.createClass({ | |
componentDidMount() { | |
const runLoop = () => { | |
this.forceUpdate(); | |
window.requestAnimationFrame(runLoop); | |
}; | |
window.requestAnimationFrame(runLoop); | |
}, | |
render() { | |
const time = new Date(); | |
return ( | |
<CanvasComponent render={renderCanvas} time={time} /> | |
); | |
} | |
}) | |
ReactDOM.render(<App />, document.getElementById('container')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment