如何使用ReactJs获得鼠标点击的X和Y坐标(百分比)



我进行了搜索,找到了以下代码,并想知道如何将其转换为在reactjs 中工作

var s = document.createElement('script');
s.setAttribute('src','https://code.jquery.com/jquery-2.1.4.min.js');
document.head.appendChild(s);
// 4. Then paste this
var oldx = 0, oldy = 0;
var newImg = $('img').attr('src');
$('img').detach();
$('body').append('<img src="' + newImg + '" style="margin:0; height:100vh; width:auto">');
$('img').off( "click" ).click(function(e) {
var offset = $(this).offset();
var x = Math.floor((e.pageX - offset.left) / $(this).width() * 10000)/100;
var y = Math.floor((e.pageY - offset.top) / $(this).height() * 10000)/100;
console.log(x, y, x - oldx, y - oldy);
oldx = x; oldy = y;
});
// 5. Click on the points you're interested. You'll get x,y coordinates in percentage of the image
// and dx and dy from the previous clicked point.
import React from 'react'

class Test extends React.Component {
constructor(props){
super(props)
this.img = React.createRef();  
}
oldx= 0; oldy = 0;
imageClick = (e) => {
var offset = this.img.current.getBoundingClientRect();
var x = Math.floor((e.pageX - offset.left) / offset.width * 10000)/100;
var y = Math.floor((e.pageY - offset.top) / offset.height * 10000)/100;
console.log(x, y, x - this.oldx, y - this.oldy);
this.oldx = x; this.oldy = y;
}

render(){
return <img onClick={this.imageClick} ref={this.img} src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" style={{margin:0, height:"100vh", width:"auto"}}></img>
}
}
export default Test;

最新更新