Reputation: 567
I'm working with mouse events on a HTML Canvas in a react component, but have an issue where the onMouseDown/onMouseUp aren't triggered with a left click on the mouse. It works for right click and center click.
handleMouseDown(event)
{
console.log("mouse down");
}
handleMouseMove(event)
{
console.log("mouse move");
}
handleMouseUp(event)
{
console.log("mouse up");
}
render() {
return (
<div
className="chart">
<canvas
id="canvas"
onMouseDown={this.handleMouseDown}
onMouseMove={this.handleMouseMove.bind(this)}
onMouseUp={this.handleMouseUp.bind(this)} />
</div>
);
Anyone experiences this before?
Edit Note: I am trying to get the X/Y coordinates of where the mouse down event occurred.
Upvotes: 3
Views: 15854
Reputation: 1136
You can use onClick
for left-clicks:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event){
const yCoord = event.y;
const xCoord = event.x;
console.log("Y Coordinate = " + yCoord +
"\n X Coordinate = " + xCoord + ".");
switch(event.which) {
case 1: {
console.log('Left Mouse button pressed.');
break;
}
case 2: {
console.log('Middle Mouse button pressed.');
break;
}
case 3: {
console.log('Right Mouse button pressed.');
break;
}
default: {
console.log('You have a strange Mouse!');
}
}
}
render() {
return (
<div className="chart">
<canvas id="canvas"
onClick={(e) =>{this.handleClick(e.nativeEvent)}}
onContextMenu={(e) =>
{this.handleClick(e.nativeEvent)}}>
</canvas>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('container')
);
.chart {
width: 100;
height: 100;
}
#canvas {
border: 1px black solid;
width: 50;
height: 50;
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Upvotes: 5