)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Distance Between Two Points (SVG)

  1. const dist = (x1, y1, x2, y2) => 
  2.   Math.sqrt(
  3.     (x1 - x2) ** 2 + 
  4.     (y1 - y2) ** 2);
  5.  
  6. const el = document.body.appendChild(
  7.   document.createElement('div')
  8. );
  9.  
  10. el.innerHTML = `
  11.   <svg style="overflow:visible;">
  12.     <circle id="circA" cx="150" cy="100" r="50" fill="gray" />
  13.     <circle id="circB" cx="150" cy="200" r="50" fill="blue" />
  14.     <text id="text" dy="20" dx="20">move mouse</text>
  15.   </svg>
  16.   <style>
  17.     body, html, svg {
  18.       width: 100%;
  19.       height: 100%;
  20.     }
  21.   </style>
  22. `;
  23.  
  24. function touch(e) {
  25.   const touches = e.touches;
  26.   let x, y;
  27.   if (touches != null && touches.length > 0) {
  28.     x = touches[0].clientX;
  29.     y = touches[0].clientY;
  30.   } else {
  31.     x = e.clientX;
  32.     y = e.clientY;
  33.   }
  34.   return { x, y };
  35. }
  36.  
  37. const hasTouch = navigator.maxTouchPoints > 0;
  38. const move = hasTouch ? 'touchmove' : 'mousemove';
  39. document.addEventListener(move, e => {
  40.   const { x, y } = touch(e);
  41.  
  42.   // using global ids :D
  43.   circB.cx.baseVal.value = x;
  44.   circB.cy.baseVal.value = y;
  45.  
  46.   const distance = dist(
  47.     circA.cx.baseVal.value, 
  48.     circA.cy.baseVal.value, x, y
  49.   );
  50.   text.innerHTML = 'move mouse, distance: ' + distance;
  51.  
  52.   circA.r.baseVal.value = distance - circB.r.baseVal.value;
  53. });

This snippet shows how to calculate the distance between two points. The dist function uses the pythagorean theorem:

  1. const dist = (x1, y1, x2, y2) => 
  2.   Math.sqrt(
  3.     (x1 - x2) ** 2 + 
  4.     (y1 - y2) ** 2);
// dom // graphics // javascript // math // svg
snippet.zone ~ 2021-24 /// {s/z}