js/jquery实现连线拖拽
先看效果图:
code:
- <!DOCTYPE html>
- <html>
- <body>
- <style type="text/css">
- body, svg{width: 100vh;
- height: 100vh;}
- svg{
- position: relative;
- }
- </style>
- <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
- <h1>My first SVG</h1>
- <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
- <circle cx="100" cy="100" r="20" stroke="black" stroke-width="1" fill="rgb(200,200,200)" />
- <rect width="40" height="40" x="300" y="100"
- style="fill:rgb(255,255,255,0.8);stroke-width:1;stroke:rgb(0,0,0,0.5)" >
- </rect>
- <line x1="0" y1="0" x2="0" y2="0" style="stroke:rgb(0,0,0);stroke-width:1"/>
- </svg>
- <script type="text/javascript">
- $(function(){
- function draw(){
- let circle = $('circle')[0];
- let rect = $('rect')[0];
- let line = $('line')[0];
- console.log(circle.cx.baseVal.value)
- console.log(circle.cy.baseVal.value)
- line.setAttribute("x1", circle.cx.baseVal.value);
- line.setAttribute("y1", circle.cy.baseVal.value);
- line.setAttribute("x2", rect.x.baseVal.value+rect.width.baseVal.value/2);
- line.setAttribute("y2", rect.y.baseVal.value+rect.height.baseVal.value/2);
- }
- function dragable(el) {
- el.mousedown(function(e1) {
- $(document).on("mousemove", function(e2){
- console.log(e2);
- el[0].setAttribute("x", e2.offsetX-el[0].width.baseVal.value/2);
- el[0].setAttribute("y", e2.offsetY-el[0].width.baseVal.value/2);
- draw();
- });
- });
- $(document).mouseup(function(e){
- $(document).off("mousemove");
- });
- }
- //init
- draw();
- dragable($('rect'));
- });
- </script>
- </body>
- </html>