繁体   English   中英

为什么文本隐藏在D3地图的状态后面?

[英]why is text hiding behind states in my D3 Map?

伊利诺伊州伤心欲绝

嗨,我几乎用d3js完成了一张地图,但是遇到了一个奇怪的问题:一些文本元素隐藏在相邻状态下。 我尝试将文本的z-index设置为高于各州的z-index 这与在文本前创建圆弧有关吗? 如果是这样,我的双手被绑住了,因为我正在使用mouseover事件显示文本。 请告知,我很好奇为什么文本显示为这种方式。

我已经在Plunkr上包含了完整的代码: http ://plnkr.co/edit/lYPWOHPACjpEq7MymII2?p=preview将鼠标悬停在印第安纳州和伊利诺伊州时,您可以看到问题

这是用于创建状态边界和使用mouseover事件添加文本的代码:

var g = svg.selectAll("path")
    .data(us.features)
    .enter()
    .append("g")

var allState = g.append("path")
    .attr("d", path)
    .attr("class", "state-boundary")
    .style("fill",function(d){console.log(d.properties.pdi);return "rgb("+ rad(d.properties.pdi) + ",0,0)"});

g.on("mouseover",function(){
    d3.select(this).append("text")
      .attr("class","states")
      .text(function(d){return d.properties.NAME})
      .attr("x",function(d){return path.centroid(d)[0]})
      .attr("y",function(d){return path.centroid(d)[1]})
      })
g.on("mouseout",function(){
    d3.select(".states")
    .remove()
})

您正在使用SVG创建地图。 在SVG(没有z-index)中,绘制顺序是定义顶部和底部的最重要的事情。

话虽这么说,这是您的问题:每个文本都被追加到<g>元素上,但是之前已经绘制了一些<g> 像这样:

<g>
    <path "Illinois path here"></path>
</g>
<g>
    <path "Indiana path here"></path>
</g>

然后,当您将鼠标悬停在伊利诺伊州上时:

<g>
    <path "Illinois path here"></path>
    <text "Illinois text here"></path>
</g>
<g>
    <path "Indiana path here"></path><!--Indiana path over Illinois text!-->
</g>

因此,解决方案非常简单:只需提高组数即可:

d3.select(this).raise().append("text")

这是您更新的插件: http ://plnkr.co/edit/EFwnO7BCHKeXvjtsIWeL?p=preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM