https://www.dashingd3js.com/svg-paths-and-d3js有这个令人敬畏但过时的例子:
//The data for our line
var lineData = [ { "x": 1, "y": 5}, { "x": 20, "y": 20},
{ "x": 40, "y": 10}, { "x": 60, "y": 40},
{ "x": 80, "y": 5}, { "x": 100, "y": 60}];
//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//The SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);
//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
如何在d3的第4版中编写该代码,最好是在typescript中编写?
所以这就是它的编写方式:
export interface XY {
y: number;
x: number;
}
drawLine(g: d3.Selection<any, any, any, any>) {
var lineData = [
{ x: 1, y: 5
}, { x: 200, y: 20
}, { x: 40, y: 10
}, { x: 60, y: 40
}, { x: 80, y: 300
}, { x: 100, y: 60
}];
var lineDude = d3.line<XY>()
.x((d) => { return (d.x); })
.y((d) => { return (d.y); });
//var svgContainer = d3.select("body")
// .append("svg")
// .attr("width", 200)
// .attr("height", 200);
var lineGraph = g.append("path")
.attr("d", lineDude(lineData))
.attr("stroke", function (d, i) {
console.log('stroke ' + i); // always 0 :-(
console.dir(d); // undefined :-(
return 'red';
})
.attr("stroke-width", 1)
.attr("fill", "none");
}
现在唯一的问题是我期望传递给笔画函数的参数'd'是XY类型的对象 - 但它是未定义的。我希望能够在一个(更复杂的)对象周围有一些逻辑,以确定每个线段使用什么颜色。