Reputation: 13952
I must be missing something incredibly simple here. I'm wanting to use d3.svg.line to draw a line between two points. The documentation is below:
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.
What I don't understand (given the lack of inline examples in the documentation) is how x1, y1, x2 and y2 fit in to the picture. All the examples using d3.svg.line
that I saw don't use them at all, and instead use a data array and a function to draw a line between multiple points (eg. http://jsfiddle.net/5e2HD/1/ and https://www.dashingd3js.com/svg-paths-and-d3js).
Whenever I try to use x1, x2, y1, and y2 in any way (eg. setting them as attributes on my line, calling them as functions, passing them as parameters, etc) I get errors. How would you use d3.svg.line
to simply create a straight line between two points, as the documentation seems to indicate it's meant for?
Upvotes: 1
Views: 2236
Reputation: 1688
Hope this helps. Check the line generator function and the last part where I am adding the path
// 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>
Upvotes: 1
Reputation: 1600
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")
Upvotes: 2