简体   繁体   中英

How can i move SVG Polygon element by mouse?

I want to move this polygon by mouse. How can i do this? I think i should use some like onMouseDown and onMouseMove get new position and transform="translate(x,y) but how can i do this by JS?

You can use draggable from jquery UI. Here is your edited code:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#Layer_1" ).draggable(); } ); </script> </head> <body> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 500" style="enable-background:new 0 0 500 500;" xml:space="preserve"> <polygon class="st0" points=" 0,5 10,0 20,5 10,10" transform="translate(90,95) rotate(0 0 0)" stroke="none" fill="red"/> </svg> </body> </html>

Take the reference from below, it's working:

HTML:

<svg id="pointer" height="50" width="50">
    <polygon points="1,1 49,10 20,20 10,49"> 
    <!-- coordinates are in x,y format -->
   <!-- points go clockwise around the polygon -->
</svg>
<a href="bbc.co.uk" target="_blank">bbc</a>

CSS:

#pointer {
  overflow: hidden;
  position: fixed;
  top: 200px;
  left: 200px;
  position: relative;
}
html {
  cursor: none;
}
a {
  font-size: 40px;
}
a:hover {
  cursor: pointer;
}

Javascript:

var mouseX;
var mouseY;
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
  event = event || window.event;
  document.getElementById('pointer').style.top=event.clientY + "px";
  document.getElementById('pointer').style.left=event.clientX + "px";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM