如何获得路径质心D3 [英] How to get a path centroid d3

查看:52
本文介绍了如何获得路径质心D3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用.centroid()方法,因为它返回[NaN,Nan].我不知道什么是正确的数据格式.

I cant use the .centroid() method because its returns [NaN,Nan]. I dont know what is the right data format.

    var pathh = d3.geo.path();
    d3.selectAll("path.line")
        .each(function (d, i) {
        var centroid = pathh.centroid(d);
        console.log('Centroid at: ', d,+ centroid[0] + ', ' + centroid[1]);
     });

我的数据格式是:一个对象是多边形的一个点(顶点)

My data format is: One object is one point(vertex) of the polygon

0: Object
   area_id: "IVP001"
   vertex_id: "37451"
   x: "100"
   y: "100"

1: Object
   area_id: "IVP001"
   vertex_id: "37452"
   x: "150"
   y: "120"

2: Object
   area_id: "IVP001"
   vertex_id: "37453"
   x: "50"
   y: "120"

有一个父数组,其中包含多边形的顶点对象.我想获取多边形的每个质心,并在其中添加文本.

There is the parent array what contains the polygon's vertex point objects. I would like to get the each centroid of the polygons, and append a text there.

我的右半解法,但是它不那么准确,而且丑陋...

My half-right solution, but its not so accurate, and its ugly...

    var areas = cg.selectAll("g.area-group")
        .data(data);    

    var ag = areas
            .enter()
            .append("g")
            .attr("class","area-group")
            .attr("data-area-id",function(d) {return d[0].area_id; });

    var area_path = ag.insert("path")
            .attr("class", "line")
            .call(dragArea);

        d3.selectAll("text").remove();




var area_id_text = areas.append("text")
            .attr("dx", function(d) {
                    var text_x = 0;
                    $.each(d, function( index, value ) { text_x += +value.x;});
                    return text_x/d.length;
              })
            .attr("dy", function(d) {
                    var text_y = 0;
                    $.each(d, function( index, value ) { text_y += +value.y; });
                    return text_y/d.length;
              })
            .text(function(d) {return d[0].area_id; })
        ;

推荐答案

您可以执行以下操作:

//calculate the centroid using the bbox
function getMyCentroid(element) {
    var bbox = element.getBBox();
    return [bbox.x + bbox.width/2, bbox.y + bbox.height/2];
}

d3.selectAll("path.line")[0].forEach(function (d, i) {
   console.log(getMyCentroid(d));
});

这篇关于如何获得路径质心D3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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