简体   繁体   中英

HTML5 canvas coordinates are giving strange angles

I want to be able to orient something toward the mouse on an HTML5 canvas. But when I use Math.atan2 and the other trig functions, the directions get messed up. It rotates in the opposite direction that it should and it's usually off by 90 degrees.

It will probably be easier if you see it for yourself. Here's the 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 );

And here's the HTML:

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

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

You can see it in action here: http://sidefofx.com/projects/stackOverflowQuestion/

How can I make the line point in the direction of the mouse?

I rechecked and what you're doing wrong (and I've done this error a few times myself) is that atan2 accepts first the y coordinate, then the x coordinate.

MDC says:

Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.

So

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

should be

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

Test updated: http://jsfiddle.net/79FaY/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM