代码之家  ›  专栏  ›  技术社区  ›  cstack

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

  •  2
  • cstack  · 技术社区  · 14 年前

    我想能够在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 回复  |  直到 14 年前
        1
  •  5
  •   Jakub Hampl    14 年前

    MDC

    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/