HTML5画布坐标给出了奇怪的角度

时间:2010-11-21 01:26:42

标签: javascript math html5 canvas trigonometry

我希望能够在HTML5画布上向鼠标定位某些东西。但是当我使用Math.atan2和其他trig函数时,方向会搞砸。它以与它应该相反的方向旋转,通常偏离90度。

如果您亲眼看到它可能会更容易。这是javascript:

var mouseX=0;
var mouseY=0;
var canvas = document.getElementById("world");
var context = canvas.getContext("2d");

function mouseMoveHandler(event) {
    mouseX = event.clientX;
    mouseY = event.clientY;
}

function windowResizeHandler() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

function loop() {
    // Clear Screen
    context.clearRect(0,0,canvas.width,canvas.height);

    // Calculate the angle to the mouse
    a = Math.atan2(mouseX-canvas.width/2,mouseY-canvas.height/2);

    // Draw a line in the direction of the mouse
    context.beginPath();
    context.fillStyle = "#000000";
    context.moveTo(canvas.width/2+10, canvas.height/2);
    context.lineTo(canvas.width/2-10, canvas.height/2);
    context.lineTo(canvas.width/2+Math.cos(a)*100, canvas.height/2+Math.sin(a)*100);
    context.fill();
}

document.addEventListener('mousemove', mouseMoveHandler, false);
window.addEventListener('resize', windowResizeHandler, false);
windowResizeHandler();
setInterval(this.loop, 1000 / 30 );

这是HTML:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id='world'></canvas>

<script type="text/javascript" src="test.js"></script>
</body>
</html>

您可以在此处看到它:http://sidefofx.com/projects/stackOverflowQuestion/

如何使线条指向鼠标方向?

1 个答案:

答案 0 :(得分:5)

我重新检查了,你做错了什么(我自己做了几次这个错误)是atan2首先接受y坐标,然后接受x坐标。

MDC说:

  

请注意,此函数的参数首先传递y坐标,然后传递x坐标。

所以

a = Math.atan2(mouseX-canvas.width/2,mouseY-canvas.height/2);

应该是

a = Math.atan2(mouseY-canvas.height/2, mouseX-canvas.width/2);

测试已更新:http://jsfiddle.net/79FaY/1/