我想做一个小绘画应用程序使用画布。所以我需要找到鼠标在画布上的位置。
当前回答
原来的答案是把它放在一个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>
其他回答
下面计算鼠标位置与canvas元素的关系:
const example = document.getElementById('example');
example.onmousemove = function(e) {
const x = e.pageX - e.currentTarget.offsetLeft;
const y = e.pageY - e.currentTarget.offsetTop;
}
你必须知道你的页面的结构,因为如果你的canvas是一个div的子div又是另一个div的子…然后,故事变得更加复杂。下面是我在2层div中创建一个canvas的代码:
canvas.addEventListener("click", function(event) {
var x = event.pageX - (this.offsetLeft + this.parentElement.offsetLeft);
var y = event.pageY - (this.offsetTop + this.parentElement.offsetTop);
console.log("relative x=" + x, "relative y" + y);
});
因为我没有找到一个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>
完整的例子
通过事件可以获得画布内的鼠标坐标。offsetX和事件。下面是一个小片段来证明我的观点:
c=document.getElementById("c"); ctx=c.getContext("2d"); ctx.fillStyle="black"; ctx.fillRect(0,0,100,100); c.addEventListener("mousemove",function(mouseEvt){ // the mouse's coordinates on the canvas are just below x=mouseEvt.offsetX; y=mouseEvt.offsetY; // the following lines draw a red square around the mouse to prove it ctx.fillStyle="black"; ctx.fillRect(0,0,100,100); ctx.fillStyle="red"; ctx.fillRect(x-5,y-5,10,10); }); body { background-color: blue; } canvas { position: absolute; top: 50px; left: 100px; } <canvas id="c" width="100" height="100"></canvas>
因为我没有找到一个解决方案,可以帮助你得到它,如果你把它附加到一个父母元素,你有一个例如选择。
这就是我所做的:
let positions = {
x: event.pageX,
y: event.pageY - event.currentTarget.getBoundingClientRect().top + event.currentTarget.offsetTop
}