Reputation: 3709
I'm trying to find the proper way to dynamically generate a path. I'm following DashingD3js' pattern for creating SVG Paths with D3js.
My question is, apart from checking each index in the accessor function and manipulating the value, and apart from creating variables that represent specific points that I want to manipulate, is there an easier way to specify dynamic line coordinates?
I have my coordinates for the path in an array of objects. I'm easily able to make the coordinates responsive using w
and h
values.
var lineData = [ {'x': 100, 'y': 0 }, {'x': w/2, 'y': -150 }, {'x': w/2, 'y': 150}, {'x': 100, 'y': 0}];
I've been able to manipulate the coordinates somewhat via the accessor function like the following.
var lineFunction = d3.svg.line()
.x(function(d, i) {
// function replacing lineData w/dynamic data
}
return d.x
})
.y(function(d) { return d.y })
.interpolate('linear');
Here's how I reference the path:
myPath
.attr('d', function() { return lineFunction(lineData); });
Is there an easier way to specify dynamic line coordinates?
Upvotes: 0
Views: 1090
Reputation: 6476
If some of the values in the linedata
array are dynamic then their values should reflect that.
For example...
function f () {return w/2;}; //assuming w is updated asynchronously
var lineData = [ {'x': 100, 'y': 0 }, {'x': f, 'y': -150 }, {'x': f, 'y': 150}, {'x': 100, 'y': 0}];
Then you just need to make the accessor aware that some of the values are functions...
var lineFunction = d3.svg.line()
.x(function(d, i) {
return typeof d.x === "function" ? d.x() : d.x;
})
.y(function(d) { return d.y })
.interpolate('linear');
Upvotes: 1