live example: https://jsfiddle.net/pdb7kraL/
-
-
Save gfortaine/f928a62c9b8ca7bcc755ebe4f9448276 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