Search code examples
javascriptsvgecmascript-5

Is there a way to identify which part of a SVG TextPath was clipped


I have a SVG textPath shown below.

<text class="text" dominant-baseline="middle" style="font-size: 0.3em">
<textPath class="text-path" href="#2abd837a-0">Cats and dogs</textPath>
</text>

This textPath is correctly showing the clipped based on the length of the path referenced by #2abd837a-0.

How would I go about using javascript to find the length of the clipped and invisible text? Is this even possible?


Solution

  • You can calculate the text length by using the getComputedTextLength method. you can calculate the path length by using the getTotalLength method.

    let textLength = elText.getComputedTextLength();
    let pathLength = abd837a.getTotalLength();
    let invisibleTextLength = textLength > pathLength ? textLength - pathLength : 0;
    
    console.log(textLength,pathLength,invisibleTextLength)
    <svg viewBox="120 100 100 100">
    <path id="abd837a" d="M 130 110 C 120 140, 180 140, 170 110" stroke="black" fill="transparent"/>
    <text id="elText" class="text" dominant-baseline="middle" style="font-size: 16px">  
      <textPath class="text-path" href="#abd837a">Cats and dogs</textPath>
    </text>
    </svg>