An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
Drag and drop SVG elements
In this article we will drag and drop SVG elements.
Lets build a site.
Lets add an SVG with two rectangles.
Lets add the CSS class to check if the element is draggable.
Add a mousedown event listener for the SVG-element.
First, check if the element has the draggable class name.
If so, get the mouse position.
Remember the element we start to drag and its position.
Then start to listen to mousemove events.
On mouse move we get the current mouse position
and we change the element position.
So the element is dragging.
When the mouse button is up we stop to listen to mouse move events.
So the element is dropped.
Lets check it out.
Drag the rectangle. Drop it.
Drag another one. Drop it.
It works! :)
const svg = document.getElementById('svg');let startX, startY, elementX, elementY, element;svg.addEventListener('mousedown', e => { const className = e.target.getAttributeNS(null, 'class'); if (className.indexOf('draggable') >= 0) { startX = e.offsetX; startY = e.offsetY; element = e.target; elementX = +element.getAttributeNS(null, 'x'); elementY = +element.getAttributeNS(null, 'y'); svg.addEventListener('mousemove', onMouseMove); } }); onMouseMove = e => { let x = e.offsetX; let y = e.offsetY; element.setAttributeNS(null, 'x', elementX + x - startX); element.setAttributeNS(null, 'y', elementY + y - startY); }; svg.addEventListener('mouseup', e => { svg.removeEventListener('mousemove', onMouseMove); });
I hope you found this article useful, if you need any help please let me know in the comment section.
See you next time. Have a nice day!
Subscribe to our channel:
https://www.youtube.com/c/Samovar101
Original Link: https://dev.to/101samovar/drag-and-drop-svg-elements-3oif
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To