js获取鼠标在canvas上实时移动的坐标点
JavaScipt
2023-08-15 10:25:23
canvas作为HTML5新增的画布标签,因其强大的功能效果和浏览器的逐步支持而大受欢迎。
本文介绍当鼠标在canvas上移动时如何实时获取到相对于画布的坐标点信息。
这里就涉及到鼠标的事件:onmousemove、onmouseout
onmousemove:事件会在鼠标指针移动到指定的对象上时发生。
onmouseout:事件会在鼠标指针移出指定的对象时发生。
本文案例中使用到的鼠标事件为onmousemove,即鼠标移动事件。通过对鼠标移动事件的监听,实时获取鼠标移动时的参数。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="cvs" style="width: 200px;height: 100px; margin-left: 100px; border: 1px solid #f00;"></canvas>
<script>
var cvs = document.getElementById('cvs');
cvs.onmousemove = function (e) {
console.log(e)
console.log('X:',e.offsetX)
console.log('Y:',e.offsetY)
};
</script>
</body>
</html>
onmousemove反馈参数说明:
pageX: 页面X坐标位置
pageY: 页面Y坐标位置
screenX: 屏幕X坐标位置
screenY: 屏幕Y坐标位置
clientX: 鼠标的坐标到页面左侧的距离
clientY: 鼠标的坐标到页面顶部的距离
offsetX:鼠标坐标到元素的左侧的距离
offsetY:鼠标坐标到元素的顶部的距离
本案例中使用到的是offsetX和offsetY,通过这两个参数可以组成当前鼠标点所在X轴和Y轴坐标数据。

891篇文章
1685人已阅读