I made a color picker using React and Canvas. Components are currently displayed in React, and the canvas is executed using javascript. I would like twice as many, so I want click events to be handled with React.
For example, this
colorStrip.addEventListener("click", click, false); function click(e) { x = e.offsetX; y = e.offsetY; var imageData = context.getImageData(x, y, 1, 1).data; rgbaColor = 'rgba(' + imageData[0] + ',' + imageData[1] + ',' + imageData[2] + ',1)'; fillGradient(); }
I would hope that I could translate into this
var ColorPicker = React.createClass({ colorStripClick: function() { //handle click events here }, render: function() { var styles = { opacity: this.props.isVisible ? '1' : '0' }; return( <div id="color-picker" style={styles}> <canvas id="color-block" height="150" width="150"></canvas> <canvas id="color-strip" height="150" width="30" onClick={this.colorStripClick}></canvas> </div> ); } });
But this does not work, because I do not know how to access the context . How can I access canvas properties using React? Is there a way to access it before clicking?
UPDATE
I used David's answer, but I was getting errors putting the function in ref , so I did ref="canvasBlock" and ref="canvasStrip" instead, and then assigned the context to componentDidMount
cocoa source share