使用D3.js计算SVG路径质心 [英] Calculate SVG Path Centroid with D3.js

查看:208
本文介绍了使用D3.js计算SVG路径质心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是位于 http://upload.wikimedia.org/wikipedia上的SVG /commons/3/32/Blank_US_Map.svg ,并与d3.js进行交互。我想创建一个点击缩放效果,如 http://bl.ocks.org/2206590 ,但该示例依赖于对存储在JSON对象中的路径数据计算质心。有没有什么方法从现有的SVG加载路径数据在现有的SVG获得质心?

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 click to zoom effect like http://bl.ocks.org/2206590, however that example relies on path data stored in a JSON object to calculate the centroid. Is there any way to load path data in d3 from an existing SVG to get the centroid?

到目前为止我的尝试(hackish):

My (hackish) attempt so far:

  function get_centroid(sel){
    var coords = d3.select(sel).attr('d');
    coords = coords.replace(/ *[LC] */g,'],[').replace(/ *M */g,'[[[').replace(/ *z */g,']]]').replace(/ /g,'],[');
    return d3.geo.path().centroid({
      "type":"Feature",
      "geometry":{"type":"Polygon","coordinates":JSON.parse(coords)}
    });
  }

这似乎适用于一些州,例如密苏里州,失败,因为我的SVG数据解析是如此基础。 d3是否支持类似这样的内容?

This seems to work on some states, such as Missouri, but others like Washington fail because my SVG data parsing is so rudimentary. Does d3 support something like this natively?

推荐答案

D3函数似乎都假设你从GeoJSON开始。但是,我实际上不认为你需要的质心这 - - 你真正需要的是边界框,幸运的是,这是直接从SVG DOM接口:

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.

这篇关于使用D3.js计算SVG路径质心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆