How to access canvas context in React
In accordance to React16 You can use React.createRef()
class ColorPicker extends React.Component {
constructor(props) {
super(props);
this.colorPickerRef = React.createRef();
}
componentDidMount() {
this.context = this.colorPickerRef.current.getContext('2d');
}
render() {
return (
<canvas ref={this.colorPickerRef} />
)
}
}
Here is the answer with react hooks:
import { useEffect, useRef } from 'react'
export default function Canvas() {
const ref = useRef()
useEffect(() => {
if (ref.current) {
const canvas = ref.current.getContext('2d')
// do something here with the canvas
}
}, [])
return <canvas ref={ref} />
}
It should just be accessing the target of the click
colorStripClick: function(e) {
var ctx = e.target.getContext('2d')
}
You can add a ref
function attribute on the canvas
element:
<canvas id="color-strip" ref={(c) => this.context = c.getContext('2d')} height="...
Then you’ll 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 to DOM node as already pointed out, but this way you’ll have access from anywhere, not just event handlers.