Calculate SVG Path Centroid with D3.js

后端 未结 3 1691
野的像风
野的像风 2020-12-05 14:32

I\'m using the SVG located at http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg in a project and interacting with it with d3.js. I\'d like to create a cli

相关标签:
3条回答
  • 2020-12-05 14:58

    The D3 functions all seem to assume you're starting with GeoJSON. However, I don't actually think you need the centroid for this - what you really need is the bounding box, and fortunately this is available directly from the SVG DOM interface:

    function getBoundingBoxCenter (selection) {
      // get the DOM element from a D3 selection
      // you could also use "this" inside .each()
      var element = selection.node();
      // use the native SVG interface to get the bounding box
      var bbox = element.getBBox();
      // return the center of the bounding box
      return [bbox.x + bbox.width/2, bbox.y + bbox.height/2];
    }
    

    This is actually slightly better than the true centroid for the purpose of zooming, as it avoids some projection issues you might otherwise run into.

    0 讨论(0)
  • 2020-12-05 14:59

    The accepted answer was working great for me until I tested in Edge. I can't comment since I don't have enough karma or whatever but was using this solution and found an issue with Microsoft Edge, which does not use x or y, just top/left/bottom/right, etc.

    So the above code should be:

    function getBoundingBoxCenter (selection) {
      // get the DOM element from a D3 selection
      // you could also use "this" inside .each()
      var element = selection.node();
      // use the native SVG interface to get the bounding box
      var bbox = element.getBBox();
      // return the center of the bounding box
      return [bbox.left + bbox.width/2, bbox.top + bbox.height/2];
    }
    
    0 讨论(0)
  • 2020-12-05 15:02

    From here

    The solution is to use the .datum() method on the selection.

    var element = d3.select("#element");
    var centroid = path.centroid(element.datum());
    
    0 讨论(0)
提交回复
热议问题