Home > Blockchain >  How to vertically center a character within a svg path?
How to vertically center a character within a svg path?

Time:08-20

I have an svg path with a text and a character like this:

<svg id="svg1" style="overflow:visible">

  <path id="path1" stroke="black" d="M 0 50 L 100 50" stroke-width="10" />
  <text text-anchor="middle"  dy="-30" >
    <textPath href="#path1" startOffset="50%" fill="red">Shape</textPath>
    <textPath href="#path1" startOffset="50%" fill="red" dominant-baseline="central" >
      <tspan font-size="30" dy="-5">⬤</tspan>
    </textPath>
  </text>
</svg>

And I want the circle (or any character in general) to align perfectly at the center of the line regardless of font-size or any other attribute

I tried changing dy but it's really isn't a universal solution.
Here's what it looks like for different browsers:

for font-size="50" in firefox
enter image description here

for font-size="50" in Brave
enter image description here

for font-size="10" in firefox & Brave
enter image description here

So how do I universally align the character to the vertical center for any given style and/or attribute?

Edit
as mentioned in the comments, I tried enter image description here

Albeit, it might be enough to check the x-height for lowercase characters.

Example 2: save ratios to data-attribute; calculate dy via js

let texts = document.querySelectorAll('text');
texts.forEach(function(text){
  let offsetRatio = parseFloat(text.getAttribute('data-offsetratio'));
  let style = window.getComputedStyle(text);
  let fontSize = parseFloat(style.fontSize);
  let dy = fontSize * offsetRatio /2;
  text.setAttribute('dy', dy );
  
})
svg{
  width:100%;
  border:1px solid #ccc
}
<svg id="svg1" style="overflow:visible" viewBox="0 30 100 40">
  <path id="path1" stroke="black" d="M 0 50 L 100 50" stroke-width="10" />
  <path id="path2" stroke="#fff" d="M 0 50 L 100 50" stroke-width="0.25" />
  <g font-size="10" style="font-family:Arial,Georgia,'Segoe UI'">
    <text data-offsetratio="0.71582" x="0" y="50" fill="red">I⬤</text>
    <text data-offsetratio="0.51855" x="15" y="50" fill="red">x</text>
  </g>
  
  <g font-size="25" style="font-family:Arial,Georgia,'Segoe UI'">
    <text data-offsetratio="0.71582" x="30" y="50" fill="red">I⬤</text>
    <text data-offsetratio="0.56409" x="60" y="50" fill="red">●</text>
    <text data-offsetratio="0.70081" x="75" y="50" fill="red">•</text>
  </g>
</svg>

  • Related