Explaining Mike Bostock's d3.js dragmove funct

2019-03-02 13:30发布

问题:

I'm currently trying to create draggable behavior in my d3 script. I'm studying Mike Bostock's example here: http://bl.ocks.org/mbostock/1557377

This is the function in question:

function dragmove(d) {
  d3.select(this)
      .attr("cx", d.x = Math.max(radius, Math.min(width - radius, d3.event.x)))
      .attr("cy", d.y = Math.max(radius, Math.min(height - radius, d3.event.y)));
}

This seems really confusing.

  • Why is this Math.max and then Math.min functionality used?

回答1:

It's being used to limit the drag range of each circle.

x is being limited to the range [radius, width-radius]

y is being limited to the range [radius, height-radius]

These are all inside an appropriately transformed svg g element so that x and y are relative to each cell. Hence the edges of the circles will cross the cell boundary when dragged.