改进SVG,使引脚在圆圈内居中,没有多个视图框

时间:2017-06-12 13:49:24

标签: svg

我有一个需要在Svg的圆圈内显示的引脚。

我目前的代码如下:

<svg viewBox="0 0 20 20" preserveAspectRatio="xMinYMin meet">
    <circle cx="50%" cy="1.5" r="1.5" style="fill: green;"></circle>
    <svg x="47.5%" y="5%" viewBox="0 0 10000 10000" fill="#fff" preserveAspectRatio="none">
        <g>
            <path d="M250,124.3c-35,0-63.4,28.8-63.4,64.1c0,35.3,28.5,64,63.4,64s63.4-28.8,63.4-64.1C313.4,153,285,124.3,250,124.3z
 M250,222c-18.3,0-33.2-15.1-33.2-33.7s14.9-33.7,33.2-33.7s33.2,15.1,33.2,33.7S268.3,222,250,222z">
            </path>
            <path d="M250,50.9c-74.9,0-135.8,61.6-135.8,137.4c0,31.3,22.5,84.4,66.9,157.7c32.9,54.4,66.2,100.3,66.6,100.7l2.4,3.3l2.4-3.3
 c0.3-0.5,33.7-46.3,66.6-100.7c44.4-73.3,66.9-126.4,66.9-157.7C385.8,112.5,324.9,50.9,250,50.9z M250,397.6
 c-16.5-24.3-45.5-68.4-69.9-114c-23.5-44-35.9-77-35.9-95.4c0-59,47.4-107,105.8-107s105.8,48,105.8,107
 c0,18.4-12.4,51.4-35.9,95.4C295.4,329.3,266.5,373.4,250,397.6z">     
            </path>
        </g>
    </svg>
</svg>

虽然有点作用,但看起来不那么优雅,也许还有马车。我想要的是一个更好的方式来集中这个组织内部&#39;不使用JavaScript的圆圈

如果我可以摆脱中间的额外SVG元素,那将是很好的,我用它来放置引脚。所以,如果你能告诉我如何只用一个g来做这个,并做一个很好的缩放功能。

1 个答案:

答案 0 :(得分:1)

如果要使用包含百分比值的坐标,则需要具有xy属性的元素。 <use>是一个元素,<g>不是。

如果以针对坐标系原点为中心绘制针脚,您的实时会更容易:translate(-250 -230)

之后,您可以轻松地将其缩放到所需的大小:scale(0.0025)(请记住:从右到左处理多个转换命令。)

最后,您使用与您的圈子具有相同xy坐标的图钉模板。

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 20 20" preserveAspectRatio="xMinYMin meet">
  <defs>
    <!--center the pin around the origin and scale it to final size-->
    <g id="pin" transform="scale(0.0025) translate(-250 -230)">
      <path d="M250,124.3c-35,0-63.4,28.8-63.4,64.1c0,35.3,28.5,64,63.4,64s63.4-28.8,63.4-64.1C313.4,153,285,124.3,250,124.3z
M250,222c-18.3,0-33.2-15.1-33.2-33.7s14.9-33.7,33.2-33.7s33.2,15.1,33.2,33.7S268.3,222,250,222z" />
      <path d="M250,50.9c-74.9,0-135.8,61.6-135.8,137.4c0,31.3,22.5,84.4,66.9,157.7c32.9,54.4,66.2,100.3,66.6,100.7l2.4,3.3l2.4-3.3
c0.3-0.5,33.7-46.3,66.6-100.7c44.4-73.3,66.9-126.4,66.9-157.7C385.8,112.5,324.9,50.9,250,50.9z M250,397.6
c-16.5-24.3-45.5-68.4-69.9-114c-23.5-44-35.9-77-35.9-95.4c0-59,47.4-107,105.8-107s105.8,48,105.8,107
c0,18.4-12.4,51.4-35.9,95.4C295.4,329.3,266.5,373.4,250,397.6z" />
    </g>
  </defs>
  <!--use the same coordinates for the center of the circle and the pin-->
  <circle cx="50%" cy="1.5" r="1.5" fill="green" />
  <use xlink:href="#pin" x="50%" y="1.5" fill="white" />
</svg>