轉載自:https://jingyan.baidu.com/article/c1a3101e5a32b3de656debbd.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>獲取鼠標在Canvas中的坐標位置</title> <style> body{text-align: center;} #canvas { border: 1px solid #ccc; width: 300px; height: 300px; overflow: hidden; margin: 0 auto; } </style> </head> <body> <div id="tips"></div> <div id="canvas" onmousemove="get_canvas(event,this)" onclick="test(event);"></div> </body> </html> <script> function get_canvas(ev, obj) { m_clientX = ev.clientX - obj.offsetLeft; m_clientY = ev.clientY - obj.offsetTop; // clientX/Y 鼠標相對當前頁面body可視區域左上角的坐標 // offsetLeft/Top 元素左上角相對父元素左上角的距離 document.getElementById("tips").innerHTML = "當前坐標:X:" + m_clientX + " ,Y:" + m_clientY; } </script>