【问题标题】:SVG textPath on circle looks like spiral on Edge?圆形上的 SVG textPath 看起来像 Edge 上的螺旋形?
【发布时间】:2019-05-23 00:04:49
【问题描述】:

我试图让一些文本适合圆形路径。这在 Firefox 和 Chrome 中可以正常工作,但是当我添加 textLength 属性时,Edge 会将文本变成螺旋状(需要它来适应整个圆圈)。

有没有办法解决这个问题,或者有什么不同的方法让文本完全合理?

(Edge 中的螺旋效果根据文本的不同而更加明显 - 从稍微向外到疯狂地偏离圆圈)

 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="220" height="220">
        <circle fill="#eeeeee" cx="110" cy="110" r="110"/>
        <path id="textpath" stroke-width="1" stroke="#000" fill="transparent" d="M170 110c0 33.137-26.863 60-60 60s-60-26.863-60-60 26.863-60 60-60 60 26.863 60 60z"/>
        <text dy="0" textLength="370" font-size="21px" fill="#444442">
          <textPath xlink:href="#textpath">Reviews * Reviews * Reviews * Reviews *</textPath>
        </text>
    </svg>

【问题讨论】:

  • 在这种情况下,您可能需要根据路径的长度重新计算字体大小的值。请看这个答案第二次更新:Animate marquee on SVG curve
  • @enxaneta 我有多个不同的文本,我需要它们具有相同的字体大小。

标签: javascript svg microsoft-edge


【解决方案1】:

尝试改变“dy”属性和“textLength”属性,修改代码如下:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="220" height="220">
    <circle fill="#eeeeee" cx="110" cy="110" r="110" />
    <path id="textpath" stroke-width="1" stroke="#000" fill="transparent" d="M170 110c0 33.137-26.863 60-60 60s-60-26.863-60-60 26.863-60 60-60 60 26.863 60 60z" />
    <text dy="-5" textLength="372" font-size="21px" fill="#444442">
        <textPath xlink:href="#textpath">Reviews * Reviews * Reviews * Reviews *</textPath>
    </text>
</svg>

Edge浏览器中的结果如下:

【讨论】:

  • 即使文本被更改,我也需要它均匀分布。这样一来,文本的任何变体都会使其偏离轨道。
  • 如果是这样的话,我认为你需要动态生成SVG元素。你可以参考this articlethis thread
【解决方案2】:

我能想到的最佳答案是使用 javascript 来检测浏览器,然后计算 letter-spacing 以使用而不是 textLength

这似乎解决了 Edge 中的问题。 IE 没有准确地获取宽度,所以有点过时了。

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent) || /MSIE 10/i.test(navigator.userAgent) || /Edge\/\d./i.test(navigator.userAgent)) {
  var textCircle = document.querySelectorAll('svg');
  for(i=0; i < textCircle.length; i++) {
    circleText(i);
  };
}
function circleText(i) {
  var str = textCircle[i].querySelector('textPath').textContent;
  var test = textCircle[i].querySelector('text').cloneNode(false);
  textCircle[i].appendChild(test);
  test.appendChild(document.createTextNode(str));
  test.removeAttribute('textLength');
  var w = test.getBBox().width;
  textCircle[i].removeChild(test);
  var dif = textCircle[i].querySelector('text').getAttribute('textLength') - w;
  textCircle[i].querySelector('text').style.letterSpacing = (dif / str.length) / 21 + 'em';
  textCircle[i].querySelector('text').removeAttribute('textLength');
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2012-05-13
    • 1970-01-01
    • 2012-12-02
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多