How to access canvas context in React

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

+5
source share
4 answers

You can add the attribute of the ref function to the canvas element:

 <canvas id="color-strip" ref={(c) => this.context = c.getContext('2d')} height="... 

Then you will have access to the context through this.context :

 colorStripClick: function() { var imageData = this.context.getImageData(x, y, 1, 1).data } 

You can also use the event object to access the DOM node, as already mentioned, but this way you have access from anywhere, not just event handlers.

+6
source

It should just access the click target.

 colorStripClick: function(e) { var ctx = e.target.getContext('2d') } 
+1
source

Like this

 colorStripClick: function (e) { var context = e.currentTarget.getContext('2d'); // your code } 

Example

+1
source

Here's the React method to remove the canvas from your component:

const canvas = ReactDOM.findDOMNode(this.refs.canvas); const context = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height);

While you can configure the DOM Node to respond, you can access the Canvas rendering API.

0
source

Source: https://habr.com/ru/post/1236840/


All Articles