我在一个项目中使用位于http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg的SVG,并与d3.js进行交互。我想创建一个像http://bl.ocks.org/2206590一样的点击缩放效果,但是这个例子依赖于存储在JSON对象中的路径数据来计算质心。有没有办法从现有的SVG加载d3中的路径数据来获得质心?
到目前为止,我的(hackish)尝试:
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本身就支持这样的东西吗?
发布于 2012-08-22 05:53:29
所有D3函数似乎都假定您是从GeoJSON开始的。然而,我实际上并不认为您需要质心-您真正需要的是边界框,幸运的是,它可以直接从SVG DOM接口获得:
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];
}
对于缩放,这实际上比真正的质心稍好一些,因为它避免了一些投影问题,否则可能会遇到一些投影问题。
发布于 2017-11-30 18:32:25
在我在Edge中测试之前,公认的答案对我来说非常有效。我不能发表评论,因为我没有足够的业力或其他什么,但我正在使用这个解决方案,并发现Microsoft Edge有一个问题,它不使用x或y,只使用top/left/bottom/right等。
所以上面的代码应该是:
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];
}
发布于 2020-04-03 04:24:41
来自here
解决方案是对选择使用.datum()方法。
var element = d3.select("#element");
var centroid = path.centroid(element.datum());
https://stackoverflow.com/questions/12062561
复制相似问题