Search code examples
svgcurveellipsestroke

How to fill SVG path with color upto a specific distance?


I have created an SVG as shown in the below image.

SVG Path

Here, I require to give color to the path only to a certain point. It is to represent the progress of a user in his journey.

  1. I searched for any SVG properties that could achieve this functionality like stroke-dashoffset, and stroke-dasharray. But, they didn't work.
  2. I tried with stroke animations, but it didn't work.

Next, I thought of achieving this by drawing another path to the required point on the existing path and give stroke to that. This would solve my problem.

But, the problem I am facing is that if the required point is on the curved portion of the path shown in the image, I cannot draw the new path exactly overlapping the previous path.

I have drawn the previous curve using this

d="M 0 130L 820 130M 820 130C 1140 130 1140 466 820 466"

To draw the new path, I was able to draw only up to M 0 130L 820 130M 820 130C x1 y1 x2 y2 1049 350

I could not draw the curve exactly because I don't know how to get the control points x1, y1, x2, and y2. I am thinking of using ellipse equation, tangents and other mathematical stuff, but I don't know how feasible it would be in this case.

Is there any straight approach for giving stroke to the first path up to the required point?

If not, how can I get the control points?


Solution

  • You can do it with stroke-dasharray:

    <svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">
    <defs>
    <style>
    path{
      stroke-width: 10;
    }
    </style>
    </defs>
    <path d="M 10 10 l 100 0 c 10 10 10 10 0 50 l -100 0" stroke="black" fill="transparent" />
    <path d="M 10 10 l 100 0 c 10 10 10 10 0 50 l -100 0" stroke="red" fill="transparent" pathLength="1" stroke-dasharray="0.6 0.4"/>
    </svg>

    You can manipulate stroke-dasharray="0.6 0.4". As long as the sum of the values is equal to pathLength, you can represent a relative length in the path.