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

标签 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元素?

最佳答案

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

关于animation - 在D3 js中将SVG坐标转换为页面坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356745/

相关文章:

jquery - 陪伴: CSS3 Animations Only Working on Load

android - 使事物在屏幕上移动的动画 (Android)

javascript - 使用数组中的文本向 SVG 元素添加工具提示

javascript - 将 SVG 嵌入 ReactJS

css - 为内联 svg 添加没有文本的下划线文本装饰

javascript - 在 WebGL + JavaScript 中更改颜色

javascript - Raphael:使用简单的无限动画逐渐减速动画

javascript - 在 d3js 中为该元素设置动画

javascript - 在 d3 中,如何从 SVG 线中获取内插线数据?

javascript - 如何检测一个元素位于另一个元素之上