How can i move SVG Polygon element by mouse?

前端 未结 2 1746
轻奢々
轻奢々 2021-01-26 05:11

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

相关标签:
2条回答
  • 2021-01-26 05:47

    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";
    }
    
    0 讨论(0)
  • 2021-01-26 05:50

    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>

    0 讨论(0)
提交回复
热议问题