admin管理员组文章数量:1393302
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
});
};
};
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
});
};
};
Share
Improve this question
asked Nov 2, 2012 at 6:10
user_78361084user_78361084
3,94824 gold badges95 silver badges162 bronze badges
2 Answers
Reset to default 3.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
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.
本文标签:
版权声明:本文标题:javascript - How do I get the x,y coordinates of the center of the circle the user mouses over? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744623180a2616152.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论