d3 draggable svg path line segment

时间:2014-06-23 21:57:38

标签: javascript svg d3.js

我的任务是使用d3在mousedown上绘制svg形状。我一直试图找出如何使它们可拖动。我得到svg线路(参见 here ),但实际上我需要使用路径。我已经非常接近,但我很难过。有人可以帮帮我吗?这是一些代码, this 是我的小提琴。

var drag = d3.behavior.drag().on('drag', dragmove);
function dragmove() {
    isDown = false;
    m3 = d3.mouse(this);
    var newArray = [ {x: (m1[0] + d3.event.dx), y: (m1[1] + d3.event.dy)},
                     {x: (m2[0] + d3.event.dx), y: (m2[1] + d3.event.dy)} ]; 
    line.attr('d', lineFunction(newArray));    
}

鼠标按下

pathArray = [ {'x': m1[0], 'y': m1[1]}, {'x': m1[0], 'y': m1[1]} ];
    line = svg.append('path')
        .attr('d', lineFunction(pathArray))
        .attr({'stroke': 'purple', 'stroke-width': 5, 'fill': 'none'})
        .call(drag);

鼠标移动

m2 = d3.mouse(this);
    pathArray[1] = {'x': m2[0], 'y': m2[1]};
    line.attr('d', lineFunction(pathArray));

2 个答案:

答案 0 :(得分:3)

嗯,我非常接近。这是我在dragmove中改变的。它现在很好用。

var newArray = [ {x: (m1[0] += d3.event.dx), y: (m1[1] += d3.event.dy)},
                 {x: (m2[0] += d3.event.dx), y: (m2[1] += d3.event.dy)} ]; 

答案 1 :(得分:2)

这是您可以拖动的路径。它与拖动其他类型的svg元素相同。

    

<head>
  <script data-require="d3@*" data-semver="3.4.6" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.6/d3.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <h1>Draggable SVG Path</h1>

  <script>
    renderPath();

    function renderPath() {

      var data = [{
        "x": 1,
        "y": 5
      }, {
        "x": 20,
        "y": 20
      }];
      var w = 200;
      var h = 200;

      var drag = d3.behavior.drag() // <-A
      .on("drag", move);

      function move(d) {
        var x = d3.event.x,
          y = d3.event.y;

        if (inBoundaries(x, y))
          d3.select(this)
            .attr("transform", function(d) {
              return "translate(" + x + ", " + y + ")";
            });
      }

      // Line creation function configured to do simple linear transformation.
      var lineFunction = d3.svg.line()
        .x(function(d) {
          return d.x;
        })
        .y(function(d) {
          return d.y;
        })
        .interpolate("linear");

      //The SVG Container
      var svgContainer = d3.select("body").append("svg")
        .attr("width", w)
        .attr("height", h);

      //The line SVG Path we draw
      var lineGraph = svgContainer.append("path")
        .attr("d", lineFunction(data))
        .attr("stroke", "blue")
        .attr("stroke-width", 2)
        .attr("fill", "none")
        .call(drag);

      function inBoundaries(x, y) {
        return (x >= (0 + 5) && x <= (w - 5)) && (y >= (0 + 5) && y <= (h - 5));
      }
    }
  </script>
</body>

</html>