How to access canvas context in React

后端 未结 6 1141
迷失自我
迷失自我 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:41

    You can add a ref function attribute on the canvas element:

     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.

提交回复
热议问题