Search code examples
javascriptsvgrecharts

How to make two gradients with different gradientUnits looks the same in recharts line chart?


Description: I have a need to apply gradient for chart lines and since straight lines with gradient is not displayed using objectBoundingBox( see SVG Line with Gradient Stroke Won't Display if vertical or horizontal - note that I can not use second suggestion from that thread and add some small number to last point since it can cause recharts related bugs ) - userSpaceOnUse was used, but it is applied not as I expected:

https://codesandbox.io/s/serverless-wildflower-y7d7gv?file=/src/App.tsx

Here we have two lines with two gradients applied to them - the only difference between those are gradientUnits. There are 6 points( 5 segments ) and offset is equal to 80%. I assume that gradient transition would happen at 4th point(Page E) and it works exactly like this with objectBoundingBox, but not with userSpaceOnUse gradient. The gradient transition point is moved and this extra offset is dynamic, so for 80% transition happens too late, for 20% it happens too early.

What I've tried:

Would appreciate any suggestions here about how it can be solved.


Solution

  • So, what helped me was moving from percentage to number coordinates. The formula is:

    x1: containerWidth - actual path width - right margin
    x2: containerWidth - rightMargin;
    

    Code sample which was referenced in question was updated using that logic.