2017-11-17 14 views
2

アニメーションツールチップを表示しようとしています。複数のグラフに対して1秒おきにその位置を変えようとしています。SVG座標をD3のページ座標に変換js

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要素としてツールチップを作成する他の方法はありますか?

+0

あなたは入力して、更新、終了パターンを使用してdiv要素を書いて考えるかもしれません - データが毎秒で来ると仮定します。 –

答えて

1

あなたのdivのツールチップが絶対的な位置にあると仮定すると、「ページ」座標はsvg要素の位置とsvg要素内の物の位置だけです。ここで

は、簡単な例(円上にマウス)です:

<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <script data-require="[email protected]" 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>

関連する問題