You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否为SVG路径中的单个虚线设置不规则样式?

实现不规则样式的SVG虚线路径

要让SVG路径的虚线呈现出每个线段略有不规则的效果,这里提供两种可行方案:

方案一:使用SVG图案(Pattern)定义不规则虚线

通过自定义包含随机长短、粗细短线段的图案,将其应用到路径描边,模拟不规则虚线效果:

<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
  <!-- 定义不规则虚线图案 -->
  <defs>
    <pattern id="irregularDash" width="20" height="10" patternUnits="userSpaceOnUse" patternContentUnits="userSpaceOnUse">
      <!-- 不同长度、粗细的短线段,模拟不规则感 -->
      <line x1="0" y1="5" x2="3" y2="5" stroke="#000" stroke-width="2"/>
      <line x1="8" y1="5" x2="12" y2="5" stroke="#000" stroke-width="1.8"/>
      <line x1="17" y1="5" x2="19" y2="5" stroke="#000" stroke-width="2.2"/>
    </pattern>
  </defs>

  <!-- 应用自定义图案的路径 -->
  <path d="M50,100 Q150,50 250,100 T350,100" fill="none" stroke="url(#irregularDash)" stroke-width="10" />
</svg>

你可以调整图案内的线段位置、长度、粗细,或者添加更多差异化短线段,让不规则效果更自然;如果是曲线路径,也可以把图案里的<line>换成短路径。

方案二:用JS生成沿主路径分布的不规则短线段

通过JS遍历主路径的长度,分段生成随机属性的小线段,实现更灵活的不规则效果:

<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
  <path id="mainPath" d="M50,100 Q150,50 250,100 T350,100" fill="none" stroke="transparent" />
  <g id="dashGroup"></g>

  <script type="text/javascript">
    const mainPath = document.getElementById('mainPath');
    const dashGroup = document.getElementById('dashGroup');
    const totalLength = mainPath.getTotalLength();
    let currentPos = 0;
    const gapRange = [5, 15]; // 间隙长度的随机范围
    const dashLengthRange = [3, 10]; // 虚线长度的随机范围
    const strokeWidthRange = [1.5, 2.5]; // 虚线粗细的随机范围

    while (currentPos < totalLength) {
      // 生成随机间隙
      const gap = Math.random() * (gapRange[1] - gapRange[0]) + gapRange[0];
      currentPos += gap;
      if (currentPos >= totalLength) break;

      // 生成随机虚线属性
      const dashLength = Math.random() * (dashLengthRange[1] - dashLengthRange[0]) + dashLengthRange[0];
      const endPos = Math.min(currentPos + dashLength, totalLength);
      const strokeWidth = Math.random() * (strokeWidthRange[1] - strokeWidthRange[0]) + strokeWidthRange[0];

      // 获取虚线的起点和终点坐标
      const startPoint = mainPath.getPointAtLength(currentPos);
      const endPoint = mainPath.getPointAtLength(endPos);

      // 创建并添加短线段
      const dash = document.createElementNS('http://www.w3.org/2000/svg', 'line');
      dash.setAttribute('x1', startPoint.x);
      dash.setAttribute('y1', startPoint.y);
      dash.setAttribute('x2', endPoint.x);
      dash.setAttribute('y2', endPoint.y);
      dash.setAttribute('stroke', '#000');
      dash.setAttribute('stroke-width', strokeWidth);
      dashGroup.appendChild(dash);

      currentPos = endPos;
    }
  </script>
</svg>

这种方法能精准控制每个虚线的随机性,甚至可以给线段坐标添加微小偏移,让不规则效果更强烈。

内容的提问来源于stack exchange,提问作者Ignas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:05:19