[英]How to get the X and Y coordinates of the mouse click in percentage using ReactJs
I went searching and found the following code and wanted to know how to convert it to work in reactjs我去搜索并找到了以下代码,并想知道如何将其转换为在 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.