如何在 React 中访问画布上下文

新手上路,请多包涵

我用 React 和 Canvas 做了一个 颜色选择器。目前,组件是在 React 中呈现的,而画布是使用 vanilla javascript 完成的。我想要两个网格更多,所以我希望用 React 处理点击事件。

例如,这个

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();
}

我希望能够翻译成这个

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>
    );
  }
});

但这不起作用,因为我不知道如何访问 context 。如何使用 React 访问画布属性?有没有办法在点击之前访问它?

更新

I used David’s answer but I was getting errors by putting a function in ref so I did ref="canvasBlock" and ref="canvasStrip" instead and then assigned the context in componentDidMount

原文由 cocoa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 355
2 个回答

您可以在 ref canvas 函数属性:

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

然后您将可以通过 this.context 访问上下文:

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

正如已经指出的那样,您还可以使用事件对象访问 DOM 节点,但这样您就可以从任何地方进行访问,而不仅仅是事件处理程序。

原文由 David Hellsing 发布,翻译遵循 CC BY-SA 3.0 许可协议

按照 React16 你可以使用 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} />
   )
}
}

原文由 Alex S 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题