将SVG坐标转换为D3 js

时间:2017-11-17 18:05:03

标签: animation d3.js svg tooltip

我试图展示一个动画工具提示,每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元素?

1 个答案:

答案 0 :(得分:1)

假设您的div工具提示绝对位置,您的"页面" coordinate只是svg元素的位置加上svg元素中thing的位置。

这是一个简单的示例(鼠标悬停在圆圈上):



<!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>
&#13;
&#13;
&#13;