Skip to content Skip to sidebar Skip to footer

D3: Draw Part Of Interpolated Path With Dashed Stroke

I'm drawing a simple interpolated line using D3.js (output as path). However, I want part of the path to have a dashed stroke if a boolean in a data point is set to true: Link to i

Solution 1:

I prepared this example for another SO question. Screenshot is here:

enter image description here

I think you have enough material there to devise a solution that fits your needs.

Take a look also at this page:

SVG Path Styling


Solution 2:

You could use stroke-dasharray to add dashes in the stroke of the generated path in the right places. That would entail finding the proper dash lengths. This can be done by calling pathElm.getPathLength() on the path up to the point where you want it to start being dashed, and to where you want it to end.

Let's say path A that is the part that is before the dashes should start. Set the d attribute with that part and call getPathLength() on it. Let's call this length a.

Append the the part of the path that should be dashed to the d attribute, then call getPathLength() again. Let's call this length b.

Create a new path element with the remaining part of the path, then call getPathLength() on that. Let's call this length c.

Construct a stroke-dasharray property string something like this:

var a = getPathLengthA();
var b = getPathLengthB();
var c = getPathLengthC();
var dasharray = a + " ";
for(var usedlen = 0; usedlen < (b-a); ) {
  dasharray += "5 10 "; // just whatever dash pattern you need
  usedlen += 15; // add the dash pattern length from the line above
}
dasharray += c;
pathElement.style.strokeDasharray = dasharray;

Here's a static example of that.


Post a Comment for "D3: Draw Part Of Interpolated Path With Dashed Stroke"