How can I click to add or drag in D3?

前端 未结 2 1658
无人共我
无人共我 2021-02-04 21:35

I get the impression this question is so simple nobody has bothered to make a demo of it, but I don\'t know enough D3 (yet) to see what I\'m doing wrong. The behavior I\'m look

2条回答
  •  有刺的猬
    2021-02-04 21:56

    First off, you definitely have the right idea for how to add points on mousedown. The two things I'd change are:

    1. Use click instead of mousedown, so if you click existing points you don't add a new point on top of the existing one.
    2. Add one point at a time, instead of re-adding all the points on each click.

    Here's a working click function:

    function click(){
      // Ignore the click event if it was suppressed
      if (d3.event.defaultPrevented) return;
    
      // Extract the click location\    
      var point = d3.mouse(this)
      , p = {x: point[0], y: point[1] };
    
      // Append a new point
      svg.append("circle")
          .attr("transform", "translate(" + p.x + "," + p.y + ")")
          .attr("r", "5")
          .attr("class", "dot")
          .style("cursor", "pointer")
          .call(drag);
    }
    

    Then, when dragging, it is simplest to move a circle using translate (which is also why I use translate when creating points above). The only real step is to extract the drag's x and y locations. Here's a working example of drag behavior.

    var drag = d3.behavior.drag()
        .on("drag", dragmove);
    
    function dragmove(d) {
      var x = d3.event.x;
      var y = d3.event.y;
      d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
    }
    

    I put all this together in this jsfiddle.

    Finally, here's a relevant SO question I read when constructing the drag example: How to drag an svg group using d3.js drag behavior?.

提交回复
热议问题