How to get a path centroid d3

断了今生、忘了曾经 提交于 2020-12-05 12:05:53

问题


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; })
        ;

回答1:


You can do something like this:

//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));
});


来源:https://stackoverflow.com/questions/33506489/how-to-get-a-path-centroid-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!