Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Last active July 30, 2017 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasboyt/bcc496c823a01ac5f648 to your computer and use it in GitHub Desktop.
Save thomasboyt/bcc496c823a01ac5f648 to your computer and use it in GitHub Desktop.
immediate-mode canvas rendering with react
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