How to access canvas context in React

后端 未结 6 1105
迷失自我
迷失自我 2021-01-11 11:26

I made a color picker with React and Canvas. Currently the components are rendered in React and canvas is done with vanilla javascript. I\'d like to two to mesh more, so I w

相关标签:
6条回答
  • 2021-01-11 11:33

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

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

    As long as you can target the DOM Node the react way, you can pretty much access the Canvas Rendering API.

    0 讨论(0)
  • 2021-01-11 11:34

    It should just be accessing the target of the click

    colorStripClick: function(e) {
      var ctx = e.target.getContext('2d')
    }
    
    0 讨论(0)
  • 2021-01-11 11:41

    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.

    0 讨论(0)
  • 2021-01-11 11:42

    Like this

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

    Example

    0 讨论(0)
  • 2021-01-11 11:52

    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} />
       )
    }
    }
    
    0 讨论(0)
  • 2021-01-11 11:58

    Here is the answer with react hooks:

    export default function Canvas() {
      const ref = React.useRef()
    
      React.useEffect(() => {
        ref.current.getContext('2d')
      }, [])
    
      return <canvas ref={ref} />
    }
    
    0 讨论(0)
提交回复
热议问题