Calculate SVG Path Centroid with D3.js

后端 未结 3 1716
野的像风
野的像风 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: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];
    }
    

提交回复
热议问题