Translate

2013년 7월 5일 금요일

[Javascript] Distance Between Two Points (두 좌표 사이의 거리 구하기)


피타고라스의 정리 (Pythagorean theorem)






Javascript


Points:  (sourceX, sourceY), (targetX, targetY)

var disX = sourceX - targetX;
var disY = sourceY - targetY;

distance = Math.sqrt(Math.abs(disX*disX) + Math.abs(disY*disY));









Example

Support only: Desktop webkit (chrome, safari)
PS. Not Support Mobile Browser (모바일 브라우저에서는 아래 예제가 실행이 되지 않습니다.)


source

<div id="groundDiv" style="position:relative; width:100%; height:500px; border:1px solid red;">
<div id="distanceValueDiv" style="position:absolute; border:1px solid black;"></div>
<div id="lineDiv" style="position:absolute; border:1px solid blue; display:none;"></div>
</div>

<script type="text/javascript">
window.addEventListener('load', function(){


var x = 0, y = 0;
var dis = 0, disX = 0, disY = 0;
var ang = 0;
var clicked = false;

var groundDiv = document.getElementById('groundDiv');
groundDiv.addEventListener('mousedown', mouseDown);
groundDiv.addEventListener('mousemove', mouseMove);
groundDiv.addEventListener('mouseup', mouseUp);

var distanceValueDiv = document.getElementById('distanceValueDiv');

var lineDiv = document.getElementById('lineDiv');
lineDiv.style.webkitTransformOrigin = '0 0';

function mouseDown(e) {
 clicked = true;
 x = e.offsetX;
 y = e.offsetY;
 
 lineDiv.style.width = '0px';
 lineDiv.style.height = '0px';
 lineDiv.style.left = x + 'px';
 lineDiv.style.top = y + 'px';
 lineDiv.style.display = '';
}
function mouseMove(e) {
 if (clicked) {
  disX = e.offsetX - x;
  disY = e.offsetY - y;
  ang = Math.atan2(disX, disY) * 180 / Math.PI;
  
  
  dis = Math.sqrt(Math.abs(disX*disX) + Math.abs(disY*disY));
  
  lineDiv.style.height = dis + 'px';
  lineDiv.style.webkitTransform = 'rotate(' + -ang + 'deg)';
  
  distanceValueDiv.style.left = e.offsetX - 40 + 'px';
  distanceValueDiv.style.top = e.offsetY - 40 + 'px';
  distanceValueDiv.innerHTML = 'distance: ' + dis;
 }
}
function mouseUp(e) {
 clicked = false;
}


});
</script>

댓글 없음 :

댓글 쓰기