javascript canvas - 鼠标位置后的线

javascript canvas - line that follow mouse position

我正在尝试在 canvas 中画一条线,从圆心开始以 360 度跟随鼠标位置。

到目前为止,这是我的代码,但我无法形成直角。任何解决方案谢谢。

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();
}); 

此公式将计算出您需要的角度。

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

工作代码段:

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>