How do I get the x,y coordinates of the center of

2019-04-16 15:10发布

I have a chart with some circles on it. When the user hovers over a circle, I want to create a mouseover event and pass the x and y coordinates of the center of that circle. How do I do that?

svg.selectAll("circle") 
      .data(data)
      .enter().append("circle")
      .attr("cx", function(d) { return x(d.number); })
      .attr("cy", function(d) { return y(d.area); })
      .call(d3.my_helper.tooltip(function(d, i){return "Area: "+ d.area;}));

d3.my_helper.tooltip = function(accessor){
            return function(selection){
                var circle_x = ???; // the center of the circle
                var circle_y = ???; // the center of the circle
                selection.on("mouseover", function(d, i){
                    // do stuff here with circle_x and circle_y
                });
            };
        }; 

2条回答
可以哭但决不认输i
2楼-- · 2019-04-16 16:06

You will need to find the offset of the svg elem itself and then add the "cy" attribute (center y) to the y coordinate and the "cx" attribute (center x) to the x coordinate accordingly:

$('circle').hover(function (ev) {
    var svgPos = $('svg').offset(),
        x = svgPos.left + $(ev.target).attr('cx'),
        y = svgPos.top + $(ev.target).attr('cy'),
        coords = [x, y];

    // coords now has your coordinates
});

If you are not using jQuery, consider using a usual hover event listener as well as .offsetTop and .offsetLeft on the element.

查看更多
霸刀☆藐视天下
3楼-- · 2019-04-16 16:09
.on('mouseover', function(d) {
    var target_x = d3.event.target.cx.animVal.value*scale + k_x;
    var target_y = d3.event.target.cx.animVal.value*scale + k_y;
}

you might need to +/- some constant k_x, k_y to correct for static offsets as well as access to the scale factor if you are using the scale method on the graph, otherwise you can ignore these

*note you probably don't want to try and mix jQuery and D3 if you can use D3 since the event properties likely contain references to the data that can be used, for example, in rendering tooltips

查看更多
登录 后发表回答