【发布时间】:2018-03-27 13:56:47
【问题描述】:
我尝试在 D3.js 和 ES6 的基础上创建自己的图表库,并带有动画和交互性。
我的问题是绘制饼图需要一些补间函数来很好地动画饼图。我尝试用 ES6 编写那些补间函数。
我的图表结构如下所示:
class PieChart {
constructor({w, h} = {}) {
this.w = w;
this.h = h;
...
this.onInit();
}
onInit() {
this.radius = Math.min(this.w, this.h) / 2;
this.arc = d3.arc()
.innerRadius(this.radius - 20)
.outerRadius(this.radius);
this.pie = d3.pie();
...
this.svg = d3.select("#id")
.append("svg")
.attr("width", this.w)
.attr("height", this.h)
this.drawChart();
}
drawChart() {
this.arcs = this.svg.append("g")
.attr("transform", `translate(${this.w / 2}, ${this.h / 2})`)
.attr("class", "slices")
.selectAll(".arc")
.data(this.dataset)
.enter()
.append("path")
.attr("d", this.arc)
.each(function(d) { this._current = d; });
...
const curryAttrTween = function() {
let outerArc = this.arc;
let radius = this.radius;
return function(d) { // <- PROBLEM: This inner function is never called
this._current = this._current || d;
let interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
let d2 = interpolate(t);
let pos = outerArc.centroid(d2);
pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
return `translate(${pos})`;
}
}
};
let labels = this.svg.select(".label-name").selectAll("text")
.data(this.pie(this.dataset), "key");
labels
.enter()
.append("text")
.attr("dy", ".35em")
.attr("class", "text")
.text((d) => `${d.data.column}: ${d.data.data.count}`);
labels
.transition()
.duration(666)
.attrTween("d", curryAttrTween.bind(this)());
labels
.exit()
.remove();
}
}
我也试过了:
drawChart() {
...
const attrTween = function(d) {
this._current = this._current || d; // <- PROBLEM: Can't access scope 'this'
let interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
let d2 = interpolate(t);
let pos = this.arc.centroid(d2);
pos[0] = this.radius * (midAngle(d2) < Math.PI ? 1 : -1);
return `translate(${pos})`;
}
}
labels
.transition()
.duration(666)
.attrTween("d", (d) => attrTween(d));
...
}
我终于尝试了:
drawChart() {
...
labels
.transition()
.duration(666)
.attrTween("d", function(d) {
this._current = this._current || d;
let interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
let d2 = interpolate(t);
let pos = this.arc.centroid(d2); // <- PROBLEM: Can't access this.arc
pos[0] = this.radius * (midAngle(d2) < Math.PI ? 1 : -1); // <- PROBLEM: Can't access this.radius
return `translate(${pos})`;
}
});
...
}
上述所有方法在某些时候都失败了。我指出了我的代码中的问题,我不确定在 ES6 中是否以及如何做到这一点。
【问题讨论】:
-
要访问第一个范围内的
const that = this;,然后在tween函数中使用that而不是this。 -
谢谢@RyanMorton,您的解决方案有效。我稍后会发布答案。
标签: javascript d3.js ecmascript-6 pie-chart es6-class