Skip to content

Svg tricks

Posted on:January 17, 2024

优化

技巧

剪裁

<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
  <clipPath id="myClip" clipPathUnits="objectBoundingBox">
    <circle cx=".5" cy=".5" r=".5" />
  </clipPath>

  <!-- 左上:应用自定义的剪切路径 -->
  <rect
    x="1"
    y="1"
    width="8"
    height="8"
    stroke="green"
    clip-path="url(#myClip)" />
</svg>

<svg viewBox="-10 -10 120 120">
  <mask id="myMask">
    <!-- 白色像素下的所有内容都将可见 -->
    <rect x="0" y="0" width="100" height="100" fill="white" />
    <!-- 黑色像素下的所有内容都将不可见 -->
    <path
      d="M10,35 A20,20,0,0,1,50,35 A20,20,0,0,1,90,35 Q90,65,50,95 Q10,65,10,35 Z"
      fill="black" />
  </mask>

  <!-- 应用此蒙版后,我们在圆圈中“打”一个心形孔 -->
  <circle cx="50" cy="50" r="50" mask="url(#myMask)" />
</svg>

描边动画

利用 stroke-dash 的性质,让空白占据所有内容,然后让空白的部分变小,内容逐渐展示出来,达到动画的效果

path {
  stroke-dasharray: 500;
  stroke-dashoffset: 0;
  animation: dash 2s linear 3s alternate infinite;
}
@keyframes dash {
    from {
        stroke-dashoffset: 500;
    }
    to {
        stroke-dashoffset: 0;
    }
}