Distance and angle between two points
by Jeado
HTML
<canvas></canvas>
<output>
<ul>
<li>Horizontal distance <span style="color:green">(x1 - x)</span>: <span id="hd"></span></li>
<li>Vertical distance <span style="color:blue">(y1 - y)</span>: <span id="vd"></span></li>
<li>Length <span style="color:red">Math.sqrt((x1-x) * (x1-x) + (y1-y) * (y1-y))</span>: <span id="length"></span> </li>
<li>Angle: Math.atan2( y1-y, x1-x ) * 180 / Math.PI: <span id="angle"></span></li>
</ul>
</output>
CSS
* {
margin: 0;
padding: 0;
font-size: 15px;
font-family: helvetica, arial, sans-serif;
}
footer, section, header, aside, figure {
display: block;
}
canvas{
background: #ccc;
}
output{display:block;position:absolute;top:0}
JavaScript
var canvas = document.querySelector('canvas'),
cx = canvas.getContext('2d'),
output = {
angle: document.querySelector('#angle'),
length: document.querySelector('#length'),
vertical: document.querySelector('#vd'),
horizontal: document.querySelector('#hd')
},
mx = my = angle = x = y = dist = grd = 0;
canvas.height = canvas.width = w = h = 400;
canvas.addEventListener('mousemove', function(ev) {
x = ev.clientX;
y = ev.clientY;
canvas.width = 400;
cx.beginPath();
cx.moveTo(200, 200);
cx.strokeStyle = 'red';
cx.lineTo(x, y);
cx.stroke();
cx.closePath();
cx.beginPath();
cx.strokeStyle = 'blue';
cx.moveTo(x, y);
cx.lineTo(x, 200);
cx.stroke();
cx.closePath();
cx.beginPath();
cx.strokeStyle = 'green';
cx.moveTo(x, 200);
cx.lineTo(200, 200);
cx.stroke();
cx.closePath();
cx.beginPath();
grd = cx.createRadialGradient(x,y,3,x,y,10);
grd.addColorStop(0, "white");
grd.addColorStop(1, "orange");
cx.fillStyle = grd;
cx.arc( x, y, 10 , 0, Math.PI*2, true );
cx.fill();
cx.closePath();
cx.beginPath();
grd = cx.createRadialGradient(200,200,3,200,200,10);
grd.addColorStop(0, "white");
grd.addColorStop(1, "red");
cx.fillStyle = grd;
cx.arc( 200, 200, 10 , 0, Math.PI*2, true );
cx.fill();
cx.closePath();
mx = x - 200;
my = y - 200;
dist = Math.sqrt(mx * mx + my * my);
angle = Math.atan2( my, mx ) * 180 / Math.PI;
output.horizontal.innerHTML = Math.abs(mx);
output.vertical.innerHTML = Math.abs(my);
output.length.innerHTML = ((dist*100)>>0)/100;
output.angle.innerHTML = ((angle*100)>>0)/100;
}, false);