如何使用 d3.js 使工具提示显示在饼图扇区附近

How to get a tooltip show up near the pie slice using d3.js?

本文关键字:扇区 显示 d3 何使用 js 工具提示      更新时间:2023-09-26

小提琴示例

如何使工具提示显示在更接近悬停切片的位置?我无法让d3.pageXOffsetd3.pageYOffset(如本例)工作。获取工具提示的悬停饼图扇区位置的方法是什么?

不工作:

path.on('mouseover', function(d) { 
    tooltip.style("top", d3.pageYOffset + "px").style("left", d3.pageXOffset + "px")
});

完整代码:

    var dataset = 
        [
            {item:"Boy",result:12},
            {item:"Girl",result:24},
            {item:"Woman",result:60},
            {item:"Man",result:10}                     
        ]
    var width = 280;
    var height = 280;
    var radius = Math.min(width, height) / 2;
    var color = d3.scale.category10();
    var svg = d3.select('#area')
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', 'translate(' + (width / 2) + 
        ',' + (height / 2) + ')');
    var arc = d3.svg.arc()
      .outerRadius(radius);
    var pie = d3.layout.pie()
      .value(function(d) { return d.result; })
      .sort(null);
    var path = svg.selectAll('path')
      .data(pie(dataset))
      .enter()
      .append('path')
      .attr('d', arc)
      .attr('fill', function(d, i) { 
        return color(d.data.item);
      });
    var tooltip = d3.select('#area').append('div').attr('class', 'tooltip');                           
    path.on('mouseover', function(d) { 
               var matrix = this.getScreenCTM()
        .translate(+this.getAttribute("cx"),
                 +this.getAttribute("cy"));
        var total = d3.sum(dataset.map(function(d) {               
          return d.result;                                           
        }));     
        var percent = Math.round(1000 * d.data.result / total) / 10; 
        tooltip.style("top", d3.pageYOffset + "px")
        .style("left",d3.pageXOffset + "px")
        .style('display', 'block') 
        .style("opacity", 1)
        .append('div')                                         
        .attr('class', 'label')                                   
        .append('div')                                        
        .attr('class', 'count')                                      
        .append('div')                                           
        .attr('class', 'percent'); 
        tooltip.select('.label').html(d.data.item);               
        tooltip.select('.count').html(d.data.result);               
        tooltip.select('.percent').html(percent + '%'); 
      });                                                           
      path.on('mouseout', function() {                             
        tooltip.style('display', 'none');                          
      });                       

使用 d3.event

tooltip.style("top", d3.event.y + "px").style("left", d3.event.x + "px");

我也会把它放到mousemove处理程序中以获得更好的结果。

更新的小提琴。