我正在使用 this blocks 制作饼图鼠标悬停时扩大饼图切片的示例。除了补间之外,我还想让饼图切片改变颜色并具有工具提示,因此我想要另一个可以与 d 和 i 一起使用的函数。
问题是,虽然 arcTween 函数按照鼠标悬停时所写的方式工作,但如果将其包装在另一个函数中,它将无法工作 - 我想这样做,以便可以访问工具提示的索引。
有人可以向我解释为什么这不起作用吗?我尝试了多种方法来返回具有不同变量的函数,但无法使其工作。
完整代码:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: #333;
fill-opacity: 90%;
stroke-width: 1.5px;
transition: fill 250ms linear;
transition-delay: 150ms;
}
path:hover {
stroke: #000;
fill-opacity: 100%;
transition-delay: 0;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [44, 16, 9, 8,8,8,4,3];
function findColor(index){
var colors = [
"#cb5b49",
"#8bbbd3",
"#1f61a3",
"#c7dae4",
"#f0d0bd",
"#e89d7b",
"#a91729",
"#408cb9"];
return colors[index];
}
var width = 960,
height = 500;
var outerRadius = height / 2 - 20,
cornerRadius = 10;
var pie = d3.layout.pie();
var arc = d3.svg.arc()
.padRadius(outerRadius);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
svg.selectAll("path")
.data(pie(data))
.enter().append("path")
.each(function(d) { d.outerRadius = outerRadius - 20; })
.attr("d", arc)
.attr("fill",function(d, i){return findColor(i)})
.on("mouseover", arcTween(outerRadius + 20, 0)) //THIS WORKS
//THE BELOW DOES NOT WORK FOR SOME REASON
// .on("mouseover", function(d,i){console.log(i); return arcTween(outerRadius + 20, 0);})
.on("mouseout", arcTween(outerRadius - 20, 150));
function arcTween(outerRadius, delay) {
return function() {
d3.select(this).transition().delay(delay).attrTween("d", function(d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function(t) { d.outerRadius = i(t); return arc(d); };
});
};
}
</script>
最佳答案
根据@LarsKotthoff,您需要这个来修复:jsfiddle.net/vndrw57a
svg.selectAll("path")
.data(pie(data))
.enter().append("path")
.each(function(d) { d.outerRadius = outerRadius - 20; })
.attr("d", arc)
.attr("fill",function(d, i){return findColor(i)})
.on("mouseover", function(){ arcTween(outerRadius + 20, 0, this)(); })
.on("mouseout", arcTween(outerRadius - 20, 150));
function arcTween(outerRadius, delay, that) {
return function() {
var el = (that !== undefined ? that : this);
d3.select(el).transition().delay(delay).attrTween("d", function(d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function(t) { d.outerRadius = i(t); return arc(d); };
});
};
关于javascript - d3 补间弧在函数调用中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704388/