【问题标题】:HTML5 canvas coordinates are giving strange anglesHTML5 画布坐标给出了奇怪的角度
【发布时间】:2011-05-13 06:22:33
【问题描述】:

我希望能够在 HTML5 画布上将某些东西指向鼠标。但是当我使用 Math.atan2 和其他三角函数时,方向会变得混乱。它以与应有的相反方向旋转,并且通常偏离 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/

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

【问题讨论】:

    标签: javascript math html canvas trigonometry


    【解决方案1】:

    我重新检查了,你做错了什么(我自己也犯过几次这个错误)是 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/

    【讨论】:

    • 这对我来说似乎很奇怪。为什么要用 sin 作为 x 坐标,用 cos 作为 y 坐标?
    • 是的,你是对的。问题在于atan2。我更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 2012-07-14
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 2016-04-25
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多