实现沿水平响应式SVG路径的元素动画并保持宽高比
解决SVG路径拉伸但沿路径动画元素保持宽高比的问题
核心思路是把需要拉伸的路径和需要保持宽高比的动画元素拆分到不同的SVG上下文:外层SVG负责路径的水平响应拉伸,内层嵌套SVG负责让星形保持原始宽高比,同时不影响沿路径的动画。
修改后的代码
.wrapper { width: 100%; min-width: 200px; max-width: 100%; height: 200px; resize: horizontal; overflow: hidden; border: 1px solid blue; } svg { width: 100%; height: 100%; } .path { fill: none; stroke: black; stroke-width: 2px; stroke-dasharray: 6 6; stroke-linecap:round; } .star { fill: red; } .inner-svg { width: 24px; /* 可根据需求调整星形显示大小 */ height: 24px; }
<div class="wrapper"> <svg viewBox="0 0 400 200" preserveAspectRatio="none"> <defs> <path id="star" d="M0,24.675L2.679,32.921L11.349,32.921L4.335,38.017L7.014,46.262L0,41.166L-7.014,46.262L-4.335,38.017L-11.349,32.921L-2.679,32.921L0,24.675Z"/> <path id="path" d="M0,36.608C0,36.608 64.096,15.519 92.956,48.531C121.816,81.542 101.293,129.283 74.824,115.941C48.354,102.599 68.017,24.7 188.557,73.454C309.097,122.207 261.935,170.513 400,175.664" vector-effect="non-scaling-stroke"/> </defs> <use href="#path" class="path"/> <!-- 嵌套SVG强制星形保持宽高比 --> <svg class="inner-svg" viewBox="-11.349 24.675 22.698 21.587" preserveAspectRatio="xMidYMid meet"> <use href="#star" class="star"> <animateMotion dur="10s" repeatCount="indefinite" rotate="auto"> <mpath href="#path"/> </animateMotion> </use> </svg> </svg> </div>
关键调整说明
- 外层SVG保留
preserveAspectRatio="none",确保路径随容器水平拉伸,vector-effect="non-scaling-stroke"保证路径描边粗细不变。 - 内层SVG设置匹配星形边界的
viewBox(取星形路径的最小/最大X、Y值计算得到),并通过默认的preserveAspectRatio="xMidYMid meet"强制星形保持原始宽高比。 - 内层SVG的宽高可直接调整,用来控制星形的显示大小,不会破坏宽高比。
这样就能同时实现:路径水平响应拉伸、星形保持原始宽高比、沿路径正常动画的效果。
内容的提问来源于stack exchange,提问作者Mushr00m
相关产品推荐
相关产品推荐

