如何使用 d3.js 使工具提示显示在饼图扇区附近
How to get a tooltip show up near the pie slice using d3.js?
小提琴示例
如何使工具提示显示在更接近悬停切片的位置?我无法让d3.pageXOffset
和d3.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
处理程序中以获得更好的结果。
更新的小提琴。
相关文章:
- 从桌面读取python文件时高亮显示代码
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何在生成下载文件时显示加载动画
- React重新渲染但未显示正确的组件
- nodejs-expressjs上传图像并显示它们
- 使用JSP从服务器检索和显示图像
- 音频控件在mouseover上显示,在mouseout上淡出
- 如何使用 d3.js 使工具提示显示在饼图扇区附近
- 放置区显示在整个表单上,即使我使用预览容器
- 使用 Raphaël JS 和 SVG 调整扇区路径大小的更优雅方法
- 拖放区未在表单中显示自身
- 拖放区.js删除在页面加载时创建的模拟文件时,会显示默认的添加文件消息
- 使用css和javascript对圆形图像的扇区进行着色处理
- D3 -地图上的中心和比例扇区
- 如何显示扇区颜色与JustGage
- 绘制圆形扇区中的随机点
- 当用户在输入区输入文本时显示警报
- html页面显示和加载事件之间的区别是什么?
- 如何使用RingCentral设置具有区号匹配的来电显示
- 拖放区.js上传框将不会显示