Javascript making image rotate to always look at mouse cursor?

前端 未结 2 880
旧时难觅i
旧时难觅i 2021-02-09 20:19

I\'m trying to get an arrow to point at my mouse cursor in javascript. Right now it just spins around violently, instead of pointing at the cursor.

Here is a fi

2条回答
  •  梦如初夏
    2021-02-09 20:46

    In the first instance, get rid of the conversion to degrees - both the Math.atan2 and the ctx.rotate functions take radians.

    That fixes the wild rotation - you still then have some math errors, which are most easily sorted out by splitting out the drawing from the math.

    The function below draws the arrow rotated by the given angle:

    // NB: canvas rotations go clockwise
    function drawArrow(angle) {
        ctx.clearRect(0, 0, cv.width, cv.height);
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(-Math.PI / 2);  // correction for image starting position
        ctx.rotate(angle);
        ctx.drawImage(arrow, -arrow.width / 2, -arrow.height / 2);
        ctx.restore();
    }
    

    and the onmove handler just figures out the direction.

    document.onmousemove = function(e) {
        var dx = e.pageX - centerX;
        var dy = e.pageY - centerY;
        var theta = Math.atan2(dy, dx);
        drawArrow(theta);
    };
    

    Note that on a canvas the Y axis points downwards (contrary to normal cartesian coordinates) so the rotations end up going clockwise instead of anti-clockwise.

    working demo at https://jsfiddle.net/alnitak/5vp0syn5/

提交回复
热议问题