Distance Between Two Points (SVG)
const dist = (x1, y1, x2, y2) =>
Math.sqrt(
(x1 - x2) ** 2 +
(y1 - y2) ** 2);
const el = document.body.appendChild(
document.createElement('div')
);
el.innerHTML = `
<svg style="overflow:visible;">
<circle id="circA" cx="150" cy="100" r="50" fill="gray" />
<circle id="circB" cx="150" cy="200" r="50" fill="blue" />
<text id="text" dy="20" dx="20">move mouse</text>
</svg>
<style>
body, html, svg {
width: 100%;
height: 100%;
}
</style>
`;
function touch(e) {
const touches = e.touches;
let x, y;
if (touches != null && touches.length > 0) {
x = touches[0].clientX;
y = touches[0].clientY;
} else {
x = e.clientX;
y = e.clientY;
}
return { x, y };
}
const hasTouch = navigator.maxTouchPoints > 0;
const move = hasTouch ? 'touchmove' : 'mousemove';
document.addEventListener(move, e => {
const { x, y } = touch(e);
// using global ids :D
circB.cx.baseVal.value = x;
circB.cy.baseVal.value = y;
const distance = dist(
circA.cx.baseVal.value,
circA.cy.baseVal.value, x, y
);
text.innerHTML = 'move mouse, distance: ' + distance;
circA.r.baseVal.value = distance - circB.r.baseVal.value;
});
This snippet shows how to calculate the distance between two points. The dist
function uses the pythagorean theorem:
const dist = (x1, y1, x2, y2) =>
Math.sqrt(
(x1 - x2) ** 2 +
(y1 - y2) ** 2);