在 D3 js 中将 SVG 坐标转换为页面坐标



我正在尝试显示一个动画工具提示,每 1 秒更改一次它的位置,用于多个图形。

var tooltip = d3.select("body")
        .append("div")
        .attr("id", "tooltip")
        .attr("class", "tooltip");

由于这是一个div,翻译将不适用于此。所以,我正在尝试像这样翻译,使用 svg 坐标。

tooltip.html("Tooltip")
            .style("left", x(currentTime) + "px")
            .style("top", height + "px");

但它将此作为页面坐标值。

如何将SVG坐标转换为页面坐标?或者有没有其他方法可以将工具提示创建为 SVG 元素?

假设你的div工具提示是绝对位置,你的"页面"坐标只是svg元素的位置加上事物在svg元素中的位置。

下面是一个快速示例(将鼠标悬停在圆圈上(:

<!DOCTYPE html>
<html>
  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>
  <body>
    <svg 
      width="300" height="300" 
      style="left: 100px; top: 100px; position: absolute">
    </svg>
    <div id="tooltip" style="position: absolute; border: 1px solid black">
      This is my tooltip
    </div>
    <script>
      var json = [
        {x: Math.random() * 300, y: Math.random() * 300},
        {x: Math.random() * 300, y: Math.random() * 300},
        {x: Math.random() * 300, y: Math.random() * 300}
      ];
      
      var svg = d3.select('svg');
      
      svg
        .selectAll('circle')
        .data(json)
        .enter()
        .append('circle')
        .attr('cx', function(d){ return d.x })
        .attr('cy', function(d){ return d.y })
        .attr('r', 30)
        .style('fill', 'red')
        .on('mouseover', function(d){
          var svgPos = svg.node().getBoundingClientRect();
          d3.select('#tooltip')
            .style('left', svgPos.left + d.x + 'px')
            .style('top', svgPos.top + d.y + 'px');
        })
      
    </script>
    
  </body>
</html>

最新更新