javascripthtmlcanvasangleradians

javascript canvas - line that follow mouse position


im trying to make line in canvas to follow mouse position in 360 degrees, starting from circle center.

This is my code so far but i cant make right angles. Any solution thanks.

https://jsfiddle.net/1L3j2vyw/

var canvas = document.getElementById('paint');
var ctx = canvas.getContext('2d');

canvas.addEventListener('mousemove',function(e){
    //mouse position
    var x = e.clientX - this.offsetLeft;
    var y = e.clientY - this.offsetTop;
    //clear canvas
    ctx.clearRect(0,0,640,640);
    //draw circle
    ctx.strokeStyle = 'yellow';
    ctx.beginPath();
    ctx.arc(200, 200, 150, 0, 2 * Math.PI);
    ctx.stroke();
    //line lenght and position
    var length = 150;
    var angle = 0;
    var newPosX = x - 200;
    var newPosY = y - 200;
    var theta = newPosY/newPosX;
    var angle = Math.atan2(-newPosX, -newPosY) * 180/Math.PI - 90;
    angle = angle < 0 ? 360 + angle : angle; 
    var pi = Math.PI;
    angle =  angle * (pi/180);
    var x2 = 200 + length * Math.cos(angle),
        y2 = 200 + length * Math.sin(angle);
    //draw line
    ctx.strokeStyle = 'blue';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(200, 200);
    ctx.lineTo(x2, y2);
    ctx.stroke();
}); 

Solution

  • This formula will calculate the angle you need.

    var angle = -Math.atan2(newPosX, newPosY) * 180 / Math.PI + 90;
    

    Working Snippet:

    var canvas = document.getElementById('paint');
    var ctx = canvas.getContext('2d');
        
    canvas.addEventListener('mousemove',function(e){
        //mouse position
        var x = e.clientX - this.offsetLeft;
        var y = e.clientY - this.offsetTop;
        //clear canvas
        ctx.clearRect(0,0,640,640);
        //draw circle
        ctx.strokeStyle = 'yellow';
        ctx.beginPath();
        ctx.arc(200, 200, 150, 0, 2 * Math.PI);
        ctx.stroke();
        //line lenght and position
        var length = 150;
        var angle = 0;
        var newPosX = x - 200;
        var newPosY = y - 200;
        var theta = newPosY/newPosX;
        var angle = -Math.atan2(newPosX, newPosY) * 180/Math.PI + 90;
        angle = angle < 0 ? 360 + angle : angle; 
        var pi = Math.PI;
        angle =  angle * (pi/180);
        var x2 = 200 + length * Math.cos(angle),
            y2 = 200 + length * Math.sin(angle);
        //draw line
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 3;
        ctx.beginPath();
        ctx.moveTo(200, 200);
        ctx.lineTo(x2, y2);
        ctx.stroke();
    }); 
    <canvas id="paint" width="640" height="640"></canvas>