是否可以在反应中获得相对于元素大小(div,img)的鼠标位置?
我已经尝试过这个
_onMouseMove(e) {
const position = this.refs.elem.getDOMNode().getBoundingClientRect();
console.log(position, e.nativeEvent.offsetX, e.screenX);
this.setState({
x: e.nativeEvent.offsetX,
y: e.nativeEvent.offsetY
});
}
答案 0 :(得分:0)
import React from 'react';
var activeMouse1 = false;
var activeMouse = false;
var posX1;
var posY2;
var pos1, pos2, pos3, pos4;
class App extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.MouseDown = this.MouseDown.bind(this);
this.state = { x: 0,
y: 0,
x1: 100,
y1: 100,
list:[],
drawingLine:undefined,
};
}
handleMouseClick1(){
activeMouse1 = true;
}
handleMouseClick(){
activeMouse = true;
}
handleMouseDown(){
activeMouse1 = false;
activeMouse = false;
}
handleMouseMove(event) {
if (this.state.drawingLine){
const drawingLine = this.state.drawingLine;
drawingLine.x2 = event.screenX /2.7;
drawingLine.y2 = event.screenY /3.8;
this.setState({drawingLine:drawingLine});
return;
}
/* if(activeMouse1 == true){
this.setState({
x: event.pageX /2.7,
y: event.pageY /3.8
});
posX1 = event.clientX /1.5;
posY2 = event.clientY /3.8;
}
if(activeMouse == true){
this.setState({
x1: event.clientX /2.7,
y1: event.clientY /3.8
});
}*/
}
MouseDown(event){
console.log("x ", event.screenX /2.7)
console.log("y ", event.screenY /3.8)
pos3 = event.screenX /2.7;
pos4 = event.screenY /3.8;
this.newLine = {x1:pos3,y1:pos4,x2:0,y2:0};
if (this.state.drawingLine){
const list = this.state.list;
list.push(this.state.drawingLine);
this.setState({list:list,drawingLine:undefined});
}else{
this.setState({drawingLine:{
x1:pos3,
y1:pos4
}})
}
}
render() {
return (
<div style={{ height: '100%', background:"green" }} >
<svg onMouseDown={this.MouseDown} onMouseUp={this.MouseUp} onMouseMove={this.handleMouseMove} xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 500 500"
xmlns="http://www.w3.org/2000/svg">
{this.state.list.map((line,i)=>
<line x1={line.x1} y1={line.y1} x2={line.x2} y2={line.y2} strokeWidth="2.5" stroke="#cccccc"/>
)}
{this.state.drawingLine && this.state.drawingLine.x2 && this.state.drawingLine.y2
? <line x1={this.state.drawingLine.x1} y1={this.state.drawingLine.y1} x2={this.state.drawingLine.x2} y2={this.state.drawingLine.y2 }
strokeWidth="2.5" stroke="#cccccc"/>
:undefined}
</svg>
</div>
);
}
}
export default App;