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

Drag Svg Circles

  1. document.addEventListener('touchmove', (e) => e.preventDefault(), {
  2.   passive: false,
  3. });
  4.  
  5. // this is just lazy - obviously goes in your stylesheet.... :P
  6. document.body.innerHTML += `
  7. <style>
  8.   body, html {
  9.     padding: 0;
  10.     height: 100%;
  11.     margin: 0;
  12.   }
  13. </style>
  14. `;
  15.  
  16. const temp = document.createElement('div');
  17. temp.innerHTML = `<svg width="100%" height="100%" viewBox="0 0 500 500"></svg>`;
  18.  
  19. const svg = document.body.appendChild(temp.querySelector('svg'));
  20.  
  21. const CIRCLE_NUM = 4;
  22.  
  23. // make some randomly positioned circles
  24. for (let i = 0; i < CIRCLE_NUM; i++) {
  25.   const x = Math.random() * 150 + 150;
  26.   const y = Math.random() * 150 + 150;
  27.   svg.innerHTML += `<circle 
  28.     cx="${x}" cy="${y}" r="60" 
  29.     stroke="#000" fill="rgba(81, 121, 200, 0.3)" 
  30.     style="cursor:pointer" />`;
  31. }
  32.  
  33. function touch(e) {
  34.   const pt = svg.createSVGPoint();
  35.   pt.x = e.clientX;
  36.   pt.y = e.clientY;
  37.   return pt.matrixTransform(svg.getScreenCTM().inverse());
  38. }
  39.  
  40. let down, ox, oy, curr;
  41. document.addEventListener('pointerdown', (e) => {
  42.   down = true;
  43.   if (e.target.tagName === 'circle') {
  44.     curr = e.target;
  45.     const { x, y } = touch(e);
  46.     ox = curr.cx.baseVal.value - x;
  47.     oy = curr.cy.baseVal.value - y;
  48.   }
  49. });
  50.  
  51. document.addEventListener('pointermove', (e) => {
  52.   if (down && curr) {
  53.     const { x, y } = touch(e);
  54.     curr.cx.baseVal.value = x + ox;
  55.     curr.cy.baseVal.value = y + oy;
  56.   }
  57. });
  58.  
  59. document.addEventListener('pointerup', (e) => {
  60.   down = false;
  61.   curr = null;
  62. });

Drag some svg circles on mobile and desktop…

// javascript // svg // ui
snippet.zone ~ 2021-24 /// {s/z}