Home > OS >  Splitting the color of a curved text along a path in svg
Splitting the color of a curved text along a path in svg

Time:01-06

I'm using SVG in HTML to draw a bended word along a path. Now that I managed to do draw the text, I need to split the word in 2 colors along the path that the word sits on. You can see the effect I'm trying to make in the image. Does anyone know how can I split the word in such a way? (I'm not sure if this matters, but the word is constantly bended, stretched and moved by the user, by modifying the "d" attribute of the path.)enter image description here

var path = document.getElementById("Path");
var textPath = document.getElementById("TextPath");
document.onmousemove = function(e){
    path.setAttribute("d", `M 100 100 q ${e.x-100} ${e.y-100} 230 0`);
    textPath.setAttribute("textLength", path.getTotalLength()   "px")
}
svg {
        width: 500px;
        height: 500px;
}
<svg>
    <path id="Path" d="M 100 100 q 50 -100 230 0" stroke="#000000" stroke-width="1" fill="none"></path>
    <text id="Text" fill="#000000" font-size="64px">
        <textPath startOffset="0%" id="TextPath" alignment-baseline="middle" href="#Path" startOffset="0%" startOffset="0%">Example</textPath>
    </text>
</svg>

Here's a simpler version of what I have now. What I want to happen, is to color everything above the curve with one color and everything below with another.

CodePudding user response:

One way of doing it: you use the text twice: once filled with color A and once filled with color B. Next you clip the second text with the path.

<svg viewBox="0 0 260 200">
  <defs>
    <path id="pth" d="M70,150 C10,40 240,40 180,150" stroke="red" fill="none" />
    <text id="txt" font-size="45" text-anchor="middle" dominant-baseline="central">
      <textPath font-size="35" startOffset="50%" href="#pth">
        SSSSSSSSSSSS
      </textPath>
    </text>
    <clipPath id="cp">
      <use href="#pth" />
    </clipPath>
  </defs>

  <use href="#txt" fill="blue" />
  <use href="#txt" fill="orange" clip-path="url(#cp)" />
</svg>

  • Related