hncl
hncl

Reputation: 2305

Kinetic JS – Draw two connected lines and measure the angle

I have developed this canvas http://jsfiddle.net/user373721/dT8qM/

It works great except, I am getting the wrong angle value. To try the example, please press down the left mouse button on the canvas, drag it to draw the first line, then release the left button, move the cursor where the second line ends (it will be great if the user can see the line being drawn) then press the mouse button again. The angle value will show; I am using the following to calculate the angle:

 angle = (Math.atan2(ay2 - ay1, ax2 - ax1)).toFixed(2);

Would appreciate your suggestions, thanks in advance.

Upvotes: 1

Views: 1366

Answers (1)

markE
markE

Reputation: 105035

Here's a function to give you the degree-angle of lines [x1,y1,x2,y2] and [x2,y2,x3,y3] assuming a clockwise sweep.

    function degreeAngle(x1,y1,x2,y2,x3,y3){
        var theta1=Math.atan2( (y1-y2),(x1-x2) );
        var theta2=Math.atan2( (y3-y2),(x3-x2) );
        var theta=(theta2-theta1)*180/Math.PI;
        theta=(theta+360)%360;
        return(theta.toFixed(2));
    }

enter image description here

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/99BBm/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    var x1=50;
    var y1=50;
    var x2=100;
    var y2=125;
    var x3=250;
    var y3=75;
    var angle=degreeAngle(x1,y1,x2,y2,x3,y3);

    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    ctx.lineTo(x3,y3);
    ctx.stroke();
    endingArrow(x2,y2,x3,y3);
    ctx.font="18px Verdana";
    ctx.fillText(angle+" degrees",40,200);

    function degreeAngle(x1,y1,x2,y2,x3,y3){
        var theta1=Math.atan2( (y1-y2),(x1-x2) );
        var theta2=Math.atan2( (y3-y2),(x3-x2) );
        var theta=(theta2-theta1)*180/Math.PI;
        theta=(theta+360)%360;
        return(theta.toFixed(2));
    }

    function endingArrow(x,y,xx,yy){
        var endRadians=Math.atan((yy-y)/(xx-x));
        endRadians+=((xx>x)?90:-90)*Math.PI/180;
        ctx.save();
        ctx.beginPath();
        ctx.translate(xx,yy);
        ctx.rotate(endRadians);
        ctx.moveTo(0,0);
        ctx.lineTo(8,20);
        ctx.lineTo(-8,20);
        ctx.closePath();
        ctx.fill();
        ctx.restore();
    }

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Upvotes: 2

Related Questions