Question

I have this problem that has been bothering me endlessly. I have this piece of code to calculate subvalues between two values:

var lineData = d3.range(from,to, 15);

Which basically gives 15 subvalues.

I am using JavaScript to draw a path between the two points.

So what has been bothering me is that this only gives me subvalues on one axis. For example between x0 and x1, but this only lets me draw in one direction.

My question is therefore if there is some sort of d3 function which lets me get the subpoints between two sets of coordinates. Something like this:

var lineData = d3.range(x_from, y_from, x_to, y_to 15);

Is this even possible?

Was it helpful?

Solution

You could use an interpolator function in combination with an array mapping function to do this.

You create an interpolator function by giving it start and end values. The resulting function takes a value from 0 to 1 and returns a result that is the corresponding distance between the start and end values.

What makes the d3 interpolator functions particularly useful for your situation is that they can interpolate objects, not just individual numbers; each property that exists in both the start and end object will be interpolated.

var iFunc = d3.interpolateObject([x1,y1], [x2,y2]);

To then create an array with a fixed number of evenly-spaced points between those two values, you need to create an array of values evenly spaced between 0 and 1, and then map those numbers to the corresponding interpolated object:

var lineData = d3.range(0, 1, 1/15).map( iFunc );

(P.S. Note that the third parameter to d3.range is the step size, not the number of steps.)

You could of course create the interpolator function in the same place you use it instead of saving it to a variable:

var lineData = d3.range(0, 1, 1/15).map(d3.interpolateObject([x1,y1], [x2,y2]) );

and your points could just as easily be key:value objects instead of arrays:

var lineData = d3.range(0, 1, 1/15).map(
                        d3.interpolateObject({x:x1, y:y1}, {x:x2, y:y2}) 
              );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top