D3: Draw part of interpolated path with dashed stroke

≯℡__Kan透↙ 提交于 2020-01-07 05:34:06

问题


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 image

An easy solution would be to just draw it with <line> segments instead - but that way I lose the interpolation.

Then I found an example from mbostock, showing how to draw a gradient along a interpolated path. I modified it to just draw transparent path fills whenever the boolean was set to true and white fills when false - while my old path is all dashed. That works (queue the above screenshot) - but by adding around thousand path elements to the DOM contra having only a single path.

It's not desirable with that many DOM elements, especially since I'm going to make more curves and the site needs to be mobile optimized. Am I missing a much simpler solution?

Wouldn't mind a modified version of mbostock's example doing the heavy calculations in advance, as long as the DOM output is simple.

Thanks!


回答1:


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.




回答2:


I prepared this example for another SO question. Screenshot is 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



来源:https://stackoverflow.com/questions/24725587/d3-draw-part-of-interpolated-path-with-dashed-stroke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!