Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <script>
- function makeDraggable(evt) {
- var svg = evt.target;
- var selectedElement = false;
- svg.addEventListener('mousedown', startDrag);
- svg.addEventListener('mousemove', drag);
- svg.addEventListener('mouseup', endDrag);
- svg.addEventListener('mouseleave', endDrag);
- function getMousePosition(evt) {
- var CTM = svg.getScreenCTM();
- return {
- x: (evt.clientX - CTM.e) / CTM.a,
- y: (evt.clientY - CTM.f) / CTM.d
- };
- }
- function startDrag(evt) {
- if (evt.target.classList.contains('draggable')) {
- selectedElement = evt.target;
- }
- }
- function drag(evt) {
- if (selectedElement) {
- evt.preventDefault();
- var coord = getMousePosition(evt);
- selectedElement.setAttributeNS(null, "x", coord.x);
- selectedElement.setAttributeNS(null, "y", coord.y);
- }
- }
- function endDrag(evt) {
- selectedElement = null;
- }
- }
- </script>
- <body>
- <svg xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 30 20" onload="makeDraggable(evt)">
- <style>
- .static {
- cursor: not-allowed;
- }
- .draggable {
- cursor: move;
- }
- svg {
- display:block;
- position:relative;
- width:400px;
- background:#1d1d1d;
- margin:20px auto;
- }
- </style>
- <rect x="0" y="0" width="30" height="20" fill="#fafafa"/> #latar
- <rect class="draggable" x="4" y="5" width="8" height="10" fill="#007bff"/> #biru
- <rect x="18" y="5" width="8" height="10" fill="#888"/> #abu
- </svg>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement