如何获得用户鼠标悬停的圆的中心的x,y坐标? [英] How do I get the x,y coordinates of the center of the circle the user mouses over?
本文介绍了如何获得用户鼠标悬停的圆的中心的x,y坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个有一些圈子的图表。当用户悬停在一个圆形上时,我想创建一个鼠标悬停事件,并传递该圆形中心的x和y坐标。我如何做?
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
});
};
};
推荐答案
您需要找到svg elem相应地将cy属性(中心y)添加到y坐标,将cx属性(中心x)添加到x坐标中:
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
});
如果您不使用jQuery,请考虑使用通常的悬停事件侦听器以及 .offsetTop
和 .offsetLeft
。
If you are not using jQuery, consider using a usual hover event listener as well as .offsetTop
and .offsetLeft
on the element.
这篇关于如何获得用户鼠标悬停的圆的中心的x,y坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文