kawazaki
kawazaki

Reputation: 31

angle between two lines with their coordinate

I want to calculate the angle between two lines which I draw with the draw line function. I have a result that seems odd (result = 2)!

var c = document.getElementById("Mycanvas");
function drawline1() {
    ctx.beginPath();
    ctx.moveTo(5, 300);
    ctx.lineTo(50, 300);
    ctx.stroke();
}

function drawline2() {
    ctx.beginPath();
    ctx.moveTo(5, 300);
    ctx.lineTo(50, 250);
    ctx.stroke();
}

function claculangle () {
    var angle1 = Math.atan2(300 - 250, 5 - 50);
    var angle2 = Math.atan2(300 - 300, 50 - 5);
    var k = angle1 - angle2;
    alert(k);
}

Upvotes: 1

Views: 1543

Answers (1)

MBo
MBo

Reputation: 80167

If you have two lines defined by points (x00,y00)-(x01,y01) and (x10,y10)-(x11,y11) then you can get angle with single atan2 call exploiting cross product and dot product of vectors

function calcangle (x00,y00,x01,y01,x10,y10,x11,y11) {
    var dx0  = x01 - x00;
    var dy0  = y01 - y00;
    var dx1  = x11 - x10;
    var dy1  = y11 - y10;
    angle = Math.atan2(dx0 * dy1 - dx1 * dy0, dx0 * dx1 + dy0 * dy1);
    writeln(angle);
    writeln(angle*180/3.1415926);
}
calcangle(5, 300, 50, 300, 5, 300, 50, 250);

gives angle in radians and degrees tested here

-0.83798122500839
-48.012788323193206

Note: this is angle to rotate the first segment to make it collinear with the second one by the shortest way, that is why value is negative. Perhaps you might need to use absolute value.

Upvotes: 4

Related Questions