【问题标题】:Convert SVG co-ordinate to page co-ordinate in D3 js将SVG坐标转换为D3 js中的页面坐标
【发布时间】:2018-05-01 14:10:07
【问题描述】:

我正在尝试为多个图表显示动画工具提示,每 1 秒更改一次位置。

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

由于这是一个 div,translate 无法使用它。所以,我试图用 svg 坐标这样翻译。

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

但是它把这个作为页面坐标值。

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

【问题讨论】:

  • 您可能会考虑使用输入、更新、退出模式编写 div - 假设数据每秒都会出现。

标签: animation d3.js svg tooltip


【解决方案1】:

假设您的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>

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2021-05-29
    • 1970-01-01
    • 2013-09-22
    • 2012-12-02
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多