gpt4 book ai didi

d3.js - D3,tooltip位置,应用viewBox时

转载 作者:行者123 更新时间:2023-12-05 04:12:22 24 4
gpt4 key购买 nike

我正在创建饼图。

悬停段时,我想显示自定义 html 工具提示 ...

从一开始,我一直在使用 d3.event.pageXd3.event.pageY 来计算工具提示位置。

但现在我想在饼图的中心点显示工具提示

enter image description here

所以,我在悬停时计算质心

 var centroid = arcs.pie.centroid(d);
var left = centroid[0];
var top = centroid[1];

并相应地分配tooltip的左、右位置

tooltip.style("left", (left) + "px")
.style("top", (top) + "px");

这仅在图表大小时有效,但我也希望图表能够响应

所以,我已经在 svg 上分配了 viewbox 属性

 var svg = d3.select(selector)
.append('svg')
.attr("viewBox", "0 0 " + attrs.svgWidth + " " + attrs.svgHeight)
.attr("preserveAspectRatio", "xMidYMid meet")

问题来了:

调整窗口大小时,图表会相应缩放,但工具提示位置不在段中心。

如何将此工具提示移动到正确的位置?

我正在寻找“无插件”解决方案。

查看 codepen

最佳答案

这里需要进行计算。首先,在获得质心后,您需要取消转换它,因为它们处于 g 转换中(并且您的 div 需要定位到顶部/左侧)。然后,您可以简单地获取 svg 的当前/实际宽度/高度,并按其与初始非 View 框宽度/高度的比例缩放位置。

var centroid = arcs.pie.centroid(d),
svgDim = svg.node().getBoundingClientRect();

var left = (centroid[0] + dynamic.marginLeft) * (svgDim.width/attrs.svgWidth),
top = (centroid[1] + dynamic.marginTop) * (svgDim.height/attrs.svgHeight);

完整运行代码如下:

function packData(p) {
var data = p;
var result = {
title: data.datasets[0].label,
data: []
};

data.labels.forEach(function(v) {
result.data.push({
label: v
});
});

result.data.forEach(function(v, i) {
v.value = data.datasets[0].data[i];

if (data.datasets[0].backgroundColor) {
v.backgroundColor = data.datasets[0].backgroundColor[i];
}

if (data.extras) {
for (var attrname in data.extras[i]) {
v[attrname] = data.extras[i][attrname];
}
}
});

return result;

}

var svg;

function drawD3JsPie(selector) {

var info = packData({
labels: ["Niger", "Cameroon", "Georgia", "Spain", "United States", "Singapore", "Qatar"],
datasets: [{
label: 'GDP Per Capita in $ (2015)',
data: [1080, 3144, 9630, 34819, 55805, 85253, 132099],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56", "#AA6384", "#2CA21B", "#678E86", "#FFAE86"]
}]
});
var data = info.data;
// ######## hard coded and dynamically calculated attributes #######

var attrs = {
svgWidth: 600,
svgHeight: 600,
marginLeft: 4,
marginBottom: 20,
marginRight: 4,
marginTop: 20,
textColor: '#7f7777',
fontSize: '13px',
pieStroke: 'white',
pieStrokeWidth: 3,
titleText: info.title,
hoverColorImpact: 1,
animationDuration: 1200,
animationEase: 'out',
titleHeight: 30,
tooltipTextColor: 'white',
tooltipBackgroundColor: 'black',

}

var dynamic = {}
dynamic.chartWidth = attrs.svgWidth - attrs.marginLeft - attrs.marginRight
dynamic.chartHeight = attrs.svgHeight - attrs.marginTop - attrs.marginBottom - attrs.titleHeight;
dynamic.pieOuterRadius = Math.min(dynamic.chartWidth, dynamic.chartHeight) / 2;
dynamic.chartTopMargin = attrs.marginTop + attrs.titleHeight;
dynamic.marginLeft = attrs.marginLeft + dynamic.pieOuterRadius;
dynamic.marginTop = dynamic.chartTopMargin + dynamic.pieOuterRadius;

// ############## SCALES #########


// ############## ARCS ###############
var arcs = {}
arcs.pie = d3.arc()
.outerRadius(dynamic.pieOuterRadius - 10)
.innerRadius(0);


// ########## layouts #######
var layouts = {};
layouts.pie = d3.pie()
.sort(null)
.value(function(d) {
return d.value;
});


//############### STARTUP ANIMATIONS ###############
var tweens = {}

tweens.pieIn = function(endData) {
var startData = {
startAngle: 0,
endAngle: 0
};
var interpolation = d3.interpolate(startData, endData);
return function(currentData) {
return arcs.pie(interpolation(currentData));
}
};


// ########### RESPONSIVE SVG DRAWING ##############
svg = d3.select(selector)
.append('svg')
.attr("viewBox", "0 0 " + attrs.svgWidth + " " + attrs.svgHeight)
.attr("preserveAspectRatio", "xMidYMid meet")



// ################# CHART CONTENT DRAWING ###############

var chart = svg.append('g')
.attr('width', dynamic.chartWidth)
.attr('height', dynamic.chartHeight)
.attr('transform', 'translate(' + (dynamic.marginLeft) + ',' + (dynamic.marginTop) + ')');


var pieArcs = chart.selectAll('.arc')
.data(layouts.pie(data))
.enter()
.append("g")
.attr("class", "arc");


pieArcs.append("path")
//.attr("d", arcs.pie)
.attr('stroke-width', attrs.pieStrokeWidth)
.attr('stroke', attrs.pieStroke)
.attr("fill", function(d) {
return d.data.backgroundColor;
})
.transition()
.duration(1000)
.attrTween("d", tweens.pieIn);






// ################ ADDING TOOLTIP ##################
var div = d3.select(selector)
.append("div")
.attr("class", "tooltip")
.style("opacity", 0)
.style("position", 'absolute')
.style("text-align", 'left')
.style("font", '12px sans-serif')
.style("background", attrs.tooltipBackgroundColor)
.style("padding", '5px')
.style("color", attrs.tooltipTextColor)
.style("border", '0px')
.style("border-radius", '4px')
.style("pointer-events", 'none')

d3.selectAll('.arc')
.on("mouseover", function(d, i) {
var centroid = arcs.pie.centroid(d),
svgDim = svg.node().getBoundingClientRect();

var left = (centroid[0] + dynamic.marginLeft) * (svgDim.width / attrs.svgWidth),
top = (centroid[1] + dynamic.marginTop) * (svgDim.height / attrs.svgHeight);

d3.select(this)
.append('circle')
.style('fill', 'steelblue')
.attr("transform", "translate(" + centroid + ")")
.attr("r", 10);

var buffer = d.value.toString().length;
if (i > data.length / 2) {
buffer = -buffer - 180;
} else {
buffer *= 4;
}
div.transition()
.duration(100)
.style("opacity", .9);

div.html("<b>" + attrs.titleText + "</b><br/>" + d.data.label + ' : ' + d.data.value)
.style("left", (left) + "px")
.style("top", (top) + "px");

var currPath = d3.select(this).select('path');
var darkenedColor = d3.rgb(currPath.attr('fill')).darker(attrs.hoverColorImpact);
currPath.attr('fill', darkenedColor);


})
.on("mouseout", function(d) {


div.transition()
.duration(200)
.style("opacity", 0);

var currPath = d3.select(this).select('path');
var changedColor = d3.rgb(currPath.attr('fill')).darker(-attrs.hoverColorImpact);
currPath.attr('fill', changedColor);

});




}

drawD3JsPie("#d3JsPie");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<div style='height:50%;width:50%'id="d3JsPie"></div>

关于d3.js - D3,tooltip位置,应用viewBox时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40708196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com