【问题标题】:Rotate svg text around central text position using css使用css围绕中心文本位置旋转svg文本
【发布时间】:2020-08-09 00:41:07
【问题描述】:

我想对 SVG 中的一组元素应用单个 css 旋转变换,以便每个元素独立旋转,而无需计算 css 中每个元素的中心。比如我有一个SVG,看起来像左边的图片,想应用css来实现右边的效果

我正在自己编写 svg,并且正在创建类似的东西

<svg baseProfile="full" height="200" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg">
    <text transform="translate(50 100)" text-anchor="middle">Text 1</text>
    <text transform="translate(100 100)" text-anchor="middle">Text 2</text>
</svg>

当我应用 css 旋转时,例如通过插入&lt;style&gt;text {transform: rotate(10deg)}&lt;/style&gt;,好像覆盖了第一个变换,旋转后的文字放在了左上角:

我可以修改 svg 以使用 `x="X" y="Y" 而不是变换属性,但这会导致变换被应用在不同的中心周围:

<svg baseProfile="full" height="200" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg">
    <style>text {transform: rotate(10deg)}</style>
    <text x="50" y="100" text-anchor="middle">Text 1</text>
    <text x="100" y="100"  text-anchor="middle">Text 2</text>
</svg>

如何构建 svg 以便我可以应用在每个元素上独立工作的旋转而不覆盖初始变换?

【问题讨论】:

    标签: css svg rotation overwrite


    【解决方案1】:

    这是一个可能的解决方案:

    -文本有 x="0" y="0" 并用 CSS 旋转。

    -您将文本放入&lt;defs&gt;

    -您使用文本并且&lt;use&gt; 元素具有您需要的xy 值。

    text{transform:rotate(90deg)}
    <svg baseProfile="full" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
      <defs>
      <text id="a" text-anchor="middle" >Text 1</text>
      <text id="b" text-anchor="middle" >Text 2</text>
      </defs>
      <use xlink:href="#a" x="50" y="50" />
      <use xlink:href="#b" x="100" y="50" />
    </svg>

    另一种解决方案(灵感来自 Robert Longson 的评论)将旋转的文本包装在 g 元素中并翻译 g

    text{transform:rotate(90deg)}
    <svg baseProfile="full" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
     
          <g transform="translate(50,50)"><text text-anchor="middle" >Text 1</text></g>
          <g transform="translate(100,50)"><text text-anchor="middle" >Text 2</text></g>
    
     </svg>

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 2014-01-24
      • 2018-08-26
      相关资源
      最近更新 更多