簡體   English   中英

d3可拖動svg路徑線段

[英]d3 draggable svg path line segment

我的任務是使用d3在mousedown上繪制svg形狀。 我一直在嘗試找出如何使其可拖動。 我把svg排了下來(請參閱此處 ),但實際上我需要使用路徑。 我已經很近了,但是我很困惑。 有人可以幫我嗎? 這是一些代碼, 是我的小提琴。

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));

好吧,我超級親密。 這就是我在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)} ]; 

這是您可以拖動的路徑。 與拖動其他類型的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM