揭秘SVG描边不随缩放改变的真相
2023-09-23 09:15:17
谈到SVG,相信大家对
<svg viewBox="0 0 300 100">
<rect x="25" y="20" width="250" height="50" style="stroke-width:10; fill:none;" />
<rect x="55" y="50" width="190" height="20" style="stroke-width:10; fill:none;" />
</svg>
从这里就可以很明显的看出来,左侧的rect元素并没有设置vector-effect,在配合上transform的scale效果后,边框明显发生了变化,右侧的rect元素设置了vector-effect为non-scaling-stroke,边框并没有发生任何改变。对于这个问题,我们可以通过设置 vector-effect: non-scaling-stroke 这个属性来解决。这个属性可以防止描边随着缩放动效改变。
当我们在SVG图像中使用描边属性时,通常会使用stroke属性来指定描边的颜色、宽度和样式。如果我们希望描边不会随着缩放动效改变,那么就可以使用vector-effect属性来设置描边的缩放方式。vector-effect属性可以接受的值包括:
- none: 描边会随着缩放动效改变。
- non-scaling-stroke: 描边不会随着缩放动效改变。
通过设置vector-effect属性为non-scaling-stroke,我们可以让描边保持不变,而不会随着缩放动效改变。这对于需要创建具有动态缩放效果的SVG图像的设计师和开发人员来说非常有用。
以下是一些使用vector-effect属性的示例:
<svg viewBox="0 0 300 100">
<rect x="25" y="20" width="250" height="50" style="stroke-width:10; fill:none;" />
<rect x="55" y="50" width="190" height="20" style="stroke-width:10; fill:none; vector-effect: non-scaling-stroke;" />
</svg>
在这个示例中,左侧的rect元素没有设置vector-effect属性,因此描边会随着缩放动效改变。右侧的rect元素设置了vector-effect属性为non-scaling-stroke,因此描边不会随着缩放动效改变。
<svg viewBox="0 0 300 100">
<circle cx="150" cy="50" r="50" style="stroke-width:10; fill:none;" />
<circle cx="150" cy="50" r="40" style="stroke-width:10; fill:none; vector-effect: non-scaling-stroke;" />
</svg>
在这个示例中,左侧的circle元素没有设置vector-effect属性,因此描边会随着缩放动效改变。右侧的circle元素设置了vector-effect属性为non-scaling-stroke,因此描边不会随着缩放动效改变。