css - 使用css围绕中心文本位置旋转svg文本

标签 css svg rotation overwrite

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

initial SVG
Desired result

我正在自己编写 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 旋转时,例如通过插入 <style>text {transform: rotate(10deg)}</style> ,好像覆盖了第一个变换,旋转后的文字放在左上 Angular :

enter image description here

我可以修改 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>

enter image description here

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

最佳答案

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

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

- 你把文字放在 <defs> .

- 您使用文本和 <use>元素具有 xy你需要的值(value)观。

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>

关于css - 使用css围绕中心文本位置旋转svg文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61425345/

相关文章:

javascript - 基于 routerLinkActive 的 Angular 高亮

html - 如何将背景图像调整为内容而不丢失部分图像(无背景大小: cover)

javascript - 为什么 SVG 不会在 chrome 扩展中加载?

c++ - 当图像在 C++ 中处于直立位置时,我如何停止不断旋转

ios - 使用移动触摸旋转 Sprite 节点

javascript - content.toggleAnimationClass();不是函数

html - 是否可以使 Html 表格的高度独立于其他表格?

javascript - 如何创建一个进度条,上面写有已完成进度和剩余进度的标签?

python - 给定整数参数Python时的字符串操作

android - 旋转图片错误: java. lang.OutOfMemoryError