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

如何为包含相邻矩形的SVG组添加外部整体描边?

为SVG组添加整体环绕描边的简洁方案

你可以用以下两种直观简洁的方式实现,比feMorphology更直接:

方案1:直接添加包围整个组的矩形

这是最简单的方法——先算出两个矩形组成的整体边界,在组内加一个覆盖整个区域的矩形,设置好描边样式即可。

根据你提供的SVG代码,两个相邻矩形的整体边界参数为:

  • x起点:36.986202
  • y起点:114.09452
  • 总宽度:75.1278(两个矩形宽度均为37.5639,直接相加)
  • 总高度:37.5639

修改后的SVG代码如下:

<g
   id="rectangles"
   transform="translate(-36.736202,-113.84452)">
   <!-- 新增的整体描边矩形,放在最底层避免遮挡内部矩形 -->
   <rect
      id="group-stroke"
      style="fill:none;stroke:#ff0000;stroke-width:1;"
      width="75.1278"
      height="37.5639"
      x="36.986202"
      y="114.09452" />
   <rect
      id="left"
      style="fill:none;stroke:#000000;stroke-width:0.5;"
      width="37.5639"
      height="37.5639"
      x="36.986202"
      y="114.09452" />   
   <rect
      id="right"
      style="fill:none;stroke:#000000;stroke-width:0.5;"
      width="37.5639"
      height="37.5639"
      x="74.550102"
      y="114.09452" />
</g>

如果希望红色描边完全在两个矩形外侧,可以调整新增矩形的参数,给描边留出空间:

<rect
   id="group-stroke"
   style="fill:none;stroke:#ff0000;stroke-width:1;"
   width="76.1278"
   height="38.5639"
   x="36.486202"
   y="113.59452" />

(这里给宽度、高度各加了1(描边宽度),x、y各减了0.5(描边宽度的一半),确保描边完全露出在外部)

方案2:用<use>复用组并添加描边

如果不想手动计算边界,可使用<use>元素复制整个组,给副本设置粗描边,再通过paint-order让描边显示在原组外侧:

<!-- 先把原组放到defs里定义 -->
<defs>
   <g
      id="rectangles-group"
      transform="translate(-36.736202,-113.84452)">
      <rect
         id="left"
         style="fill:none;stroke:#000000;stroke-width:0.5;"
         width="37.5639"
         height="37.5639"
         x="36.986202"
         y="114.09452" />   
      <rect
         id="right"
         style="fill:none;stroke:#000000;stroke-width:0.5;"
         width="37.5639"
         height="37.5639"
         x="74.550102"
         y="114.09452" />
   </g>
</defs>

<!-- 先渲染带红色描边的组副本 -->
<use href="#rectangles-group" style="fill:none;stroke:#ff0000;stroke-width:1;paint-order:stroke;" />
<!-- 再渲染原组,覆盖在描边之上 -->
<use href="#rectangles-group" />

这种方法无需手动计算边界,适合元素位置可能动态变化的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:03:27