如何在React中访问画布上下文 [英] How to access canvas context in React
问题描述
我使用React和Canvas制作了一个颜色选择器。目前,组件在React中呈现,canvas使用vanilla javascript完成。我想两个网格更多,所以我希望点击事件用React处理。
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 want the click events to be handled with 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>
);
}
});
但这不起作用,因为我不知道如何访问上下文
。如何使用React访问画布属性?有没有办法在点击之前访问它?
But that doesn't work because I don't know how to access context
. How can I get access to the canvas properties with React? Is there a way to access it before the click?
更新
我使用了大卫的答案,但是我通过放置一个错误来收到错误函数在 ref
所以我做了 ref =canvasBlock
和 ref =canvasStrip
改为然后在 componentDidMount
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
推荐答案
<分配上下文p>您可以在 canvas
元素上添加 ref
函数属性:
You can add a ref
function attribute on the canvas
element:
<canvas id="color-strip" ref={(c) => this.context = c.getContext('2d')} height="...
然后你将通过 this.context
访问上下文:
Then you’ll have access to the context through this.context
:
colorStripClick: function() {
var imageData = this.context.getImageData(x, y, 1, 1).data
}
您也可以使用事件对象访问已经指出的DOM节点,但这样您就可以从任何地方访问,而不仅仅是事件处理程序。
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.
这篇关于如何在React中访问画布上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!