Drag Svg Circles
document.addEventListener('touchmove', (e) => e.preventDefault(), {
passive: false,
});
// this is just lazy - obviously goes in your stylesheet.... :P
document.body.innerHTML += `
<style>
body, html {
padding: 0;
height: 100%;
margin: 0;
}
</style>
`;
const temp = document.createElement('div');
temp.innerHTML = `<svg width="100%" height="100%" viewBox="0 0 500 500"></svg>`;
const svg = document.body.appendChild(temp.querySelector('svg'));
const CIRCLE_NUM = 4;
// make some randomly positioned circles
for (let i = 0; i < CIRCLE_NUM; i++) {
const x = Math.random() * 150 + 150;
const y = Math.random() * 150 + 150;
svg.innerHTML += `<circle
cx="${x}" cy="${y}" r="60"
stroke="#000" fill="rgba(81, 121, 200, 0.3)"
style="cursor:pointer" />`;
}
function touch(e) {
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
return pt.matrixTransform(svg.getScreenCTM().inverse());
}
let down, ox, oy, curr;
document.addEventListener('pointerdown', (e) => {
down = true;
if (e.target.tagName === 'circle') {
curr = e.target;
const { x, y } = touch(e);
ox = curr.cx.baseVal.value - x;
oy = curr.cy.baseVal.value - y;
}
});
document.addEventListener('pointermove', (e) => {
if (down && curr) {
const { x, y } = touch(e);
curr.cx.baseVal.value = x + ox;
curr.cy.baseVal.value = y + oy;
}
});
document.addEventListener('pointerup', (e) => {
down = false;
curr = null;
});
Drag some svg circles on mobile and desktop…