d3 - 了解 d3.svg.line 的文档

d3 - understanding the documentation for d3.svg.line

我一定是遗漏了一些非常简单的东西。我想使用 d3.svg.line 在两点之间画一条线。文档如下:

svg:line x1="0" y1="0" x2="0" y2="0" The line element defines a line segment that starts at one point and ends at another. The first point is specified using the x1 and y1 attributes, while the second point is specified using the x2 and y2 attributes. The line element is a popular choice for drawing rules, reference lines, axes and tick marks.

我不明白(鉴于文档中缺少内联示例)是 x1、y1、x2 和 y2 如何适合图片。我看到的所有使用 d3.svg.line 的示例根本没有使用它们,而是使用数据数组和函数在 多个点 之间画一条线(例如。 http://jsfiddle.net/5e2HD/1/ and https://www.dashingd3js.com/svg-paths-and-d3js).

每当我尝试以任何方式使用 x1、x2、y1 和 y2(例如,将它们设置为我的行上的属性、将它们作为函数调用、将它们作为参数传递等)时,我都会出错。您将如何使用 d3.svg.line 在两点之间简单地创建一条直线,正如文档似乎表明的那样?

var svg = d3.select("body").append("svg") .attr("width", 500) .attr("height", 500); svg.append("line").attr("x1",200).attr("y1",200).attr("x2",400).attr("y2",400).attr("style","stroke:rgb(255,0,0);stroke-width:2")

希望这对您有所帮助。检查线生成器功能和我添加路径的最后一部分

// The data for our line
var lineData = [{
    x: 50,
    y: 50
}, {
    x: 50,
    y: 100
}, {
    x: 100,
    y: 150
}, {
    x: 150,
    y: 175
}, {
    x: 225,
    y: 175
}];

// Set the size of our graph
var w = 500;
var h = 500;
var padding = 10;


// Line generator function
var line = d3.svg.line()
    .x(function (d) {
    return d.x;
})
    .y(function (d) {
    return d.y;
})


// SVG container
var svg = d3.select('#line')
    .append('svg')
    .attr({
    width: w,
    height: h
});

// Add the path
var path = svg.append('path')
    .attr("d", line(lineData))
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .attr("fill", "none");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="line"></div>