2015-02-23 84 views
-1

我正在创建一个网站,其中包含一组允许用户绘制不同类型图表的人员。我现在正在开发工作分解树(WBT)图表,并且遇到了svg元素的问题。创建可通过从角落拖动来调整大小的svg元素

我希望能够允许用户通过从角上拖动形状来调整画布上的元素。

我在网上搜索了几个小时寻找合适的解决方案,但似乎无法找到任何东西。

任何人都可以帮我吗?

感谢

+0

请[告诉我们你的代码](http://stackoverflow.com/help/mcve),以便我们可以看到[你到目前为止所尝试的](http://whathaveyoutried.com)。 – GoBusto 2015-02-23 14:41:54

+0

你没有提供太多的细节和示例代码。但是让我们假设你在svg中有一个矩形。现在你需要绑定3个鼠标事件mousedown,mouseup和mousemove。在mousemove改变矩形尺寸。 (一旦我访问我的电脑,我会给代码示例。) – RashFlash 2015-02-23 17:12:21

回答

0

确定这里就是我想出的代码,它不是最好的,但它会帮助你了解我们如何能做到“调整”

的jsfiddle在这里http://jsfiddle.net/sv66bxee/

我的HTML代码: -

<div style="border: 2px solid;width: 800px;"> 
     <svg id="mycanvas" width="800px" height="500px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > 
     <rect id="myrect" fill="black" x="100" y="70" width="100" height="100" /> 

     <rect id="resize" fill="red" x="190" y="160" width="20" height="20" /> 
     </svg> 
    </div> 

和一些JavaScript: -

document.addEventListener('mousedown', mousedown, false); 

     var mousedown_points; 
     function mousedown(e) { 

      var target = e.target; 
      if (target.id === 'resize') { 
       mousedown_points = { 
        x: e.clientX, 
        y: e.clientY 
       } 
       document.addEventListener('mouseup', mouseup, false); 
       document.addEventListener('mousemove', mousemove, false); 
      } 
     } 

     function mousemove(e) { 
      var current_points = { 
       x: e.clientX, 
       y: e.clientY 
      } 

      var rect= document.getElementById('myrect'); 
      var w=parseFloat(rect.getAttribute('width')); 
      var h=parseFloat(rect.getAttribute('height')); 

      var dx=current_points.x-mousedown_points.x; 
      var dy=current_points.y-mousedown_points.y; 

      w+=dx; 
      h+=dy; 

      rect.setAttribute('width',w); 
      rect.setAttribute('height',h); 

      mousedown_points=current_points; 

      updateResizeIcon(dx,dy); 
     } 

     function updateResizeIcon(dx,dy){ 
      var resize= document.getElementById('resize'); 
      var x=parseFloat(resize.getAttribute('x')); 
      var y=parseFloat(resize.getAttribute('y')); 

      x+=dx; 
      y+=dy; 

      resize.setAttribute('x',x); 
      resize.setAttribute('y',y); 
     } 


     function mouseup(e) { 
      document.removeEventListener('mouseup', mouseup, false); 
      document.removeEventListener('mousemove', mousemove, false); 
     } 
相关问题