如何在允许SVG自身缩放的同时保留SVG内部元素的长宽比?

Eri*_*ric 5 html html5 svg

我是SVG的新手,如果这是一个明显的问题,我深表歉意。我修补了几个小时,似乎撞墙了。

我正在尝试在HTML文档中创建SVG元素,该元素包括:

  • 在外部视口上有牢固的边界
  • 保留内部元素的长宽比
  • 不保留外部SVG元素的长宽比
  • 可以在保持这些矛盾的同时任意调整大小

这个JSFiddle说明了我的意思和我尝试过的事情:

http://jsfiddle.net/a8q6S/

这是相同的代码,因为否则我无法发布此代码:

<div>
     <h2>correct placement and aspect ratio, but cannot be resized without losing relative placement</h2>

    <svg viewBox="0 0 100 100" style="width: 100px; height: 100px; border: 1px solid red;">
        <circle cx="0" cy="0" r="10"></circle>
        <circle cx="50" cy="50" r="10"></circle>
        <circle cx="100" cy="100" r="10"></circle>
    </svg>
</div>
<div>
     <h2>correct aspect ratio of circle, incorrect relative placement</h2>

    <svg viewBox="0 0 100 100" preserveAspectRatio="xMinYMin" style="width: 200px; height: 100px; border: 1px solid red;">
        <circle cx="0" cy="0" r="10"></circle>
        <circle cx="50%" cy="50%" r="10"></circle>
        <circle cx="100%" cy="100%" r="10"></circle>
    </svg>
</div>
<div>
     <h2>correct relative placement, can be resized, but loses internal aspect ratio</h2>

    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style="width: 200px; height: 100px; border: 1px solid red;">
        <circle cx="0" cy="0" r="10"></circle>
        <circle cx="50" cy="50" r="10"></circle>
        <circle cx="100" cy="100" r="10"></circle>
    </svg>
</div>
Run Code Online (Sandbox Code Playgroud)

这可能吗?我会以错误的方式处理吗?

Pau*_*eau 0

使用纯 SVG 无法实现您想要的效果。您将需要使用一些 javascript 在加载和调整大小时稍微调整 SVG。

如果您使用类似于第二个示例的内容,则只需调整 viewBox、宽度和高度。内容可以保持不变。

例如,

<svg viewBox="0 0 100 100" style="width: 100px; height: 100px; border: 1px solid red;">
    <circle cx="0" cy="0" r="10"></circle>
    <circle cx="50%" cy="50%" r="10"></circle>
    <circle cx="100%" cy="100%" r="10"></circle>
</svg>
Run Code Online (Sandbox Code Playgroud)

会成为

<svg viewBox="0 0 200 100" style="width: 200px; height: 100px; border: 1px solid red;">
    <circle cx="0" cy="0" r="10"></circle>
    <circle cx="50%" cy="50%" r="10"></circle>
    <circle cx="100%" cy="100%" r="10"></circle>
</svg>
Run Code Online (Sandbox Code Playgroud)

当宽度加倍时。

http://jsfiddle.net/a8q6S/3/