我正在尝试扩展在我的饼图中创建的圆弧的外半径。我无法在鼠标悬停时看到如何执行此操作。我试图用我之前制作的更大的 outerRadius 制作一个新弧线 (bArc),并将其应用于我的路径属性“d”
d3.select(this).select("path").attr("d", bArc);
在路径上的鼠标悬停事件中
path.on("mouseover", function(d){
但无济于事,控制台也没有报错。我有点不知所措,我能找到的关于这个主题的所有资源似乎都过时了,而且不推荐使用 v4。
我做了这个 fiddle :
最佳答案
这一行...
d3.select(this).select("svg").attr("d", bArc);
...没有什么意义。您必须将更改应用到 DOM 元素,即 this
。因此,应该是:
d3.select(this).attr("d", bArc);
当您执行 mouseout
时,不要忘记将 d
属性改回来。
这是您的代码,其中包含这些更改:
var data = [{
label: '0-24%',
color: "#ff875e",
highlight: "#ff7a4d",
value: 3,
},
{
label: '25%-49%',
color: "#f6bc58",
highlight: "#f5b13d",
value: 1,
},
{
label: '50%-74%',
color: "#eae860",
highlight: "#e7e54b",
value: 2,
},
{
label: '75%-100%',
color: "#85d280",
highlight: "#80d07b",
value: 3,
}
];
var tooltip = d3.select('body')
.append('div')
.attr('class', 'tooltip2')
.style("opacity", 0);
var width = 360;
var height = 360;
var radius = Math.min(width, height) / 2.5;
var outerRadius = height / 2 - 20;
//D3 allows colours to be defined as a range, beneath is input the ranges in same order as our data set above. /Nicklas
var color = d3.scaleOrdinal()
.range(['#ff875e', '#f6bc58', '#eae860', '#85d280']);
var svg = d3.select('#piechart2')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.arc()
.innerRadius(0)
.outerRadius(radius)
.padAngle(.05)
.padRadius(radius / 5);
var bArc = d3.arc()
.innerRadius(0)
.outerRadius(radius * 1.1)
.padAngle(.05)
.padRadius(radius / 5);
var pie = d3.pie()
.value(function(d) {
return d.value;
})
.sort(null);
var path = svg.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d) {
return color(d.data.color);
});
path.transition()
.duration(500)
.attrTween("d", tweenPie);
path.on("mouseover", function(d) {
tooltip.transition()
.duration(200)
.style("opacity", .9)
.style("display", null)
.text(d.data.label + ": " + d.data.value);
d3.select(this).transition()
.duration(500)
.style('fill', d.data.highlight)
.attr("d", bArc);
});
path.on("mousemove", function() {
tooltip.style("top", (event.pageY - 10) + "px").style("left", (event.pageX + 10) + "px");
});
path.on("mouseout", function(d) {
d3.select(this).transition()
.duration(500)
.style('fill', d.data.color)
.attr("d", arc);
tooltip.transition()
.duration(300)
.style("opacity", 0);
});
function tweenPie(b) {
b.innerRadius = 0;
var i = d3.interpolate({
startAngle: 0,
endAngle: 0
}, b);
return function(t) {
return arc(i(t));
};
}
.tooltip2 {
position: absolute;
text-align: center;
width: auto;
height: 28px;
padding: 2px;
font: 18px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="piechart2" style="text-align:center; margin-bottom:1em;">
</div>
关于javascript - 无法更改圆弧的半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46444788/