开发者

HTML5 canvas coordinates are giving strange angles

开发者 https://www.devze.com 2023-01-25 22:22 出处:网络
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 th

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'></canva开发者_JAVA百科s>

<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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号