[英]How do I calculate the angle at which mouse pointer is present to a certain point?
How do I calculate the angle at which the mouse pointer is present relative to the screen right bottom corner?如何计算鼠标指针相对于屏幕右下角的角度?
Add an event listener for mousemove
, get the coordinates of the mouse with event.pageX
and event.pageY
, and use Math.atan2
to calculate the angle:为mousemove
添加事件监听,通过event.pageX
和event.pageY
获取鼠标坐标,并使用Math.atan2
计算角度:
var angle = document.getElementById("angle"); var p2 = { x: window.innerWidth, y: window.innerHeight }; document.addEventListener("mousemove", function(e) { var p1 = { x: e.pageX, y: e.pageY }; var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI; angle.innerHTML = Math.round(angleDeg); })
Angle: <span id="angle">[move mouse first!]</span>
We can take it one step further by playing around with HTML5 Canvas using CanvasRenderingContext2D.arc()
and CanvasRenderingContext2D.lineTo()
:我们可以通过使用CanvasRenderingContext2D.arc()
和CanvasRenderingContext2D.lineTo()
玩弄 HTML5 Canvas 更进一步:
var canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var ctx = canvas.getContext("2d"); ctx.font = "15px Arial"; ctx.fillText("Move your cursor over the canvas to get started", 10, 30); var p2 = { x: window.innerWidth, y: window.innerHeight }; document.addEventListener("mousemove", function(e) { ctx.clearRect(0, 0, canvas.width, canvas.height); var p1 = { x: e.pageX, y: e.pageY }; ctx.beginPath(); ctx.moveTo(canvas.width, canvas.height); ctx.lineTo(p1.x, p1.y); ctx.stroke(); var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI; var a = p1.x - p2.x; var b = p1.y - p2.y; var c = Math.sqrt(a * a + b * b); ctx.beginPath(); ctx.moveTo(canvas.width, canvas.height); ctx.arc(canvas.width, canvas.height, 50, 1 * Math.PI, 1 * Math.PI + (2 / 360 * Math.round(angleDeg) * Math.PI), false); ctx.closePath(); ctx.stroke(); ctx.fillText(Math.round(angleDeg)+"°", canvas.width - 70, canvas.height - 20); })
body, html { margin: 0; height: 100%; }
<canvas id="canvas"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.