Jolin
Jolin

Reputation: 1615

d3.js line().x(x).y(y)

I am studying the bezier curve from this demo, in the beginning it defines a series variables like this

var w = 250,
    h = 300,
    t = .5,
    delta = .01,
    padding = 10,
    points = [{x: 10, y: 250}, {x: 0, y: 0}, {x: 100, y: 0}, {x: 200, y: 250}, {x: 225, y: 125}], 

    bezier = {},
    line = d3.svg.line().x(x).y(y),
    n = 4,
    stroke = d3.scale.category20b(),
    orders = d3.range(2, n + 2);

I have no idea what does line = d3.svg.line().x(x).y(y) mean, can anyone explain?

Upvotes: 2

Views: 10825

Answers (1)

John Ledbetter
John Ledbetter

Reputation: 14183

Check out the fantastic d3js documentation on d3.svg.line().

d3.svg.line() returns a function that can be called with input data points and returns a SVG Path describing a line. The x/y values of the items in the input are determined by the values passed to line().x() and line().y(), which could be functions or constants. Normally they'll be a d3.scale().

For example,

var data = [{x: 1, y: 3}, {x: 50, y: 100}, {x: 100, y: 0}];
var x = d3.scale.linear().domain([0, 200]).range([0, 20]);
var y = d3.scale.linear().domain([0, 100]).range([0, 10]);
var line = d3.svg.line()
  .x(function(d){ return x(d.x); })
  .y(function(d){ return y(d.y); });

line(data);

Will return "M0.1,0.3L5,10L10,0", which can be assigned to the d attribute of an svg:path and describes a line going through the points 0.1,0.3 5,10 and 10,0.

Upvotes: 10

Related Questions