Advertisement
yudiwbs

cobadragdrop

Sep 6th, 2019
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Title</title>
  6.  
  7.     <script>
  8.         function makeDraggable(evt) {
  9.             var svg = evt.target;
  10.             var selectedElement = false;
  11.             svg.addEventListener('mousedown', startDrag);
  12.             svg.addEventListener('mousemove', drag);
  13.             svg.addEventListener('mouseup', endDrag);
  14.             svg.addEventListener('mouseleave', endDrag);
  15.             function getMousePosition(evt) {
  16.                 var CTM = svg.getScreenCTM();
  17.                 return {
  18.                     x: (evt.clientX - CTM.e) / CTM.a,
  19.                     y: (evt.clientY - CTM.f) / CTM.d
  20.                 };
  21.             }
  22.             function startDrag(evt) {
  23.                 if (evt.target.classList.contains('draggable')) {
  24.                     selectedElement = evt.target;
  25.                 }
  26.             }
  27.             function drag(evt) {
  28.                 if (selectedElement) {
  29.                     evt.preventDefault();
  30.                     var coord = getMousePosition(evt);
  31.                     selectedElement.setAttributeNS(null, "x", coord.x);
  32.                     selectedElement.setAttributeNS(null, "y", coord.y);
  33.                 }
  34.             }
  35.             function endDrag(evt) {
  36.                 selectedElement = null;
  37.             }
  38.         }
  39.     </script>
  40. <body>
  41. <svg xmlns="http://www.w3.org/2000/svg"
  42.      viewBox="0 0 30 20" onload="makeDraggable(evt)">
  43.  
  44.     <style>
  45.         .static {
  46.             cursor: not-allowed;
  47.         }
  48.         .draggable {
  49.             cursor: move;
  50.         }
  51.         svg {
  52.             display:block;
  53.             position:relative;
  54.             width:400px;
  55.             background:#1d1d1d;
  56.             margin:20px auto;
  57.         }
  58.     </style>
  59.  
  60.     <rect x="0" y="0" width="30" height="20" fill="#fafafa"/>  #latar
  61.     <rect class="draggable" x="4" y="5" width="8" height="10" fill="#007bff"/>   #biru
  62.     <rect x="18" y="5" width="8" height="10"   fill="#888"/>  #abu
  63. </svg>
  64. </body>
  65. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement