Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Created July 25, 2014 19:14
Show Gist options
  • Save sebmarkbage/6f7da234174ab9f64cce to your computer and use it in GitHub Desktop.
Save sebmarkbage/6f7da234174ab9f64cce to your computer and use it in GitHub Desktop.
Canvas Drawing Example
/** @jsx React.DOM */
var Graphic = React.createClass({
componentDidMount: function() {
var context = this.getDOMNode().getContext('2d');
this.paint(context);
},
componentDidUpdate: function() {
var context = this.getDOMNode().getContext('2d');
context.clearRect(0, 0, 200, 200);
this.paint(context);
},
paint: function(context) {
context.save();
context.translate(100, 100);
context.rotate(this.props.rotation, 100, 100);
context.fillStyle = '#F00';
context.fillRect(-50, -50, 100, 100);
context.restore();
},
render: function() {
return <canvas width={200} height={200} />;
}
});
var App = React.createClass({
getInitialState: function() {
return { rotation: 0 };
},
componentDidMount: function() {
requestAnimationFrame(this.tick);
},
tick: function() {
this.setState({ rotation: this.state.rotation + .01 });
requestAnimationFrame(this.tick);
},
render: function() {
return <div><Graphic rotation={this.state.rotation} /></div>
}
});
React.renderComponent(<App />, document.body);
@mattm
Copy link

mattm commented Jan 18, 2015

Very helpful, appreciate it.

@darul75
Copy link

darul75 commented Jan 13, 2016

very good, thx again

@Tattomoosa
Copy link

Note that getDOMNode is deprecated, use findDOMNode now.

And you may have to use the syntax ReactDOM.findDOMNode(this).getContext('2d) instead, depending on your React implementation.

@sakthikanth
Copy link

How to view this output in node js ?

@sakthikanth
Copy link

Where will you run this program?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment