【发布时间】:2021-03-08 14:48:18
【问题描述】:
例如,图片中有一些圆圈相互重叠,如果鼠标悬停在重叠区域上,我想获取有关这两个特征/圆圈的信息。
代码和工具提示示例附在下面。
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = 32;
var circles = d3.range(20).map(function() {
return {
x: Math.round(Math.random() * (width - radius * 2) + radius),
y: Math.round(Math.random() * (height - radius * 2) + radius)
};
});
var color = d3.scaleOrdinal()
.range(d3.schemeCategory20);
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
svg.selectAll("circle")
.data(circles)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", radius)
.on("mouseover", function(d){
return tooltip.style("visibility", "visible");
})
.on("mousemove", function(d){
return tooltip
.html("Radius: " + d.x)
.style("top", (event.pageY-10)+"px").style("left", (event.pageX+10)+"px");
})
.on("mouseout", function(d){return tooltip.style("visibility", "hidden");})
.style("fill", function(d, i) { return color(i); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function dragstarted(d) {
d3.select(this).raise().classed("active", true);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("active", false);
}
svg {
border: 1px solid black;
}
.active {
stroke: #000;
stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<svg width="960" height="500"></svg>
【问题讨论】:
-
请为您的代码添加一个可运行的minimal reproducible example,并告诉我们您的尝试。另见How to Ask!
-
好的,我很快就会添加。
-
嗨@RubenHelsloot 我添加了代码sn-p。如果你能帮上忙,请指导我。谢谢
-
我真的很喜欢这个问题。这不会有一个简单的答案。有时间我会研究的。
标签: javascript d3.js mouseover