我想做一个小绘画应用程序使用画布。所以我需要找到鼠标在画布上的位置。
当前回答
下面计算鼠标位置与canvas元素的关系:
const example = document.getElementById('example');
example.onmousemove = function(e) {
const x = e.pageX - e.currentTarget.offsetLeft;
const y = e.pageY - e.currentTarget.offsetTop;
}
其他回答
function myFunction(e) {
var x = e.clientX - e.currentTarget.offsetLeft ;
var y = e.clientY - e.currentTarget.offsetTop ;
}
这可以正常工作!
摘自本教程,感谢上面的评论做了更正:
function getMousePos( canvas, evt ) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.floor( ( evt.clientX - rect.left ) / ( rect.right - rect.left ) * canvas.width ),
y: Math.floor( ( evt.clientY - rect.top ) / ( rect.bottom - rect.top ) * canvas.height )
};
}
在画布上使用如下:
var canvas = document.getElementById( 'myCanvas' );
canvas.addEventListener( 'mousemove', function( evt ) {
var mousePos = getMousePos( canvas, evt );
} );
因为我没有找到一个jquery免费的答案,我可以复制/粘贴,这里是我使用的解决方案:
document.getElementById('clickme').onclick = function(e) { // e = Mouse click event. var rect = e.target.getBoundingClientRect(); var x = e.clientX - rect.left; //x position within the element. var y = e.clientY - rect.top; //y position within the element. console.log("Left? : " + x + " ; Top? : " + y + "."); } #clickme { margin-top: 20px; margin-left: 100px; border: 1px solid black; cursor: pointer; } <div id="clickme">Click Me -<br> (this box has margin-left: 100px; margin-top: 20px;)</div>
完整的例子
原来的答案是把它放在一个iframe中。更好的解决方案是在填充设置为0px的画布上使用事件offsetX和offsetY。
<html>
<body>
<script>
var main=document.createElement('canvas');
main.width="200";
main.height="300";
main.style="padding:0px;margin:30px;border:thick dashed red";
document.body.appendChild(main);
// adding event listener
main.addEventListener('mousemove',function(e){
var ctx=e.target.getContext('2d');
var c=Math.floor(Math.random()*0xFFFFFF);
c=c.toString(16); for(;c.length<6;) c='0'+c;
ctx.strokeStyle='#'+c;
ctx.beginPath();
ctx.arc(e.offsetX,e.offsetY,3,0,2*Math.PI);
ctx.stroke();
e.target.title=e.offsetX+' '+e.offsetY;
});
// it worked! move mouse over window
</script>
</body>
</html>
我实现了另一个解决方案,我认为很简单,所以我想和你们分享一下。
所以,对我来说,问题是拖动的div将跳转到0,0的鼠标光标。所以我需要捕捉鼠标在div上的位置来调整div的新位置。
我读取的divs PageX和PageY,并设置的顶部和左侧的根据,然后得到的值,调整坐标,以保持光标在div的初始位置,我使用onDragStart监听器和存储e.nativeEvent.layerX和e.nativeEvent.layerY,只有在初始触发器给你的鼠标位置在可拖动的div。
示例代码:
onDrag={(e) => {
let newCoords;
newCoords = { x: e.pageX - this.state.correctionX, y: e.pageY - this.state.correctionY };
this.props.onDrag(newCoords, e, item.id);
}}
onDragStart={
(e) => {
this.setState({
correctionX: e.nativeEvent.layerX,
correctionY: e.nativeEvent.layerY,
});
}
我希望这能帮助那些和我经历过同样问题的人:)