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

查看:29
本文介绍了使用 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加载d3中的路径数据以获得质心?

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天全站免登陆