如何调整SVG图形的点击区域,避免相邻图形点击区域重叠?
问题描述

我已用虚线标出位于上方的黑色图形的边界。目前的问题是,在黑色图形与蓝色图形的重叠区域,我希望点击触发的是蓝色图形而非黑色图形,即仅能点击每个图形的可见区域。
我已尝试解决该问题数小时,但始终无法成功。
现有代码
CSS
.rotate { transform: rotate(180deg); position: relative; margin-left: -71px; top: 1px; }
HTML
<svg viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg" pointer-events="visiblePainted"> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="#000eee" stroke="black" cursor="pointer" pointer-events="visiblePainted" id="shape1"/> </svg> <svg class="rotate" viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg" pointer-events="visiblePainted"> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="currentColor" stroke="black" cursor="pointer" pointer-events="visiblePainted" id="shape2"/> </svg>
解决方案
核心是让上方黑色图形仅响应自身未被蓝色图形覆盖区域的点击,以下是几种可行方法:
方法一:裁剪路径(clipPath)
给上方黑色图形添加裁剪路径,只保留不重叠的可见区域:
<svg viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg"> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="#000eee" stroke="black" cursor="pointer" id="shape1"/> </svg> <svg class="rotate" viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg"> <defs> <clipPath id="clipShape2"> <!-- 用偶数非零规则,保留两个路径不重叠的部分 --> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z M1.5 1.5L66.5 66.5H131.5L66.5 1.5Z" fill-rule="evenodd"/> </clipPath> </defs> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="currentColor" stroke="black" cursor="pointer" clip-path="url(#clipShape2)" id="shape2"/> </svg>
裁剪路径中包含黑色图形原始路径和蓝色图形旋转后的路径,通过fill-rule="evenodd"自动排除重叠区域,仅保留可见部分响应点击。
方法二:单SVG内路径差集运算
将两个图形合并到同一个SVG中,利用路径填充规则实现差集:
<svg viewBox="0 0 133 67" width="133" height="67" xmlns="http://www.w3.org/2000/svg"> <!-- 蓝色图形 --> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="#000eee" stroke="black" cursor="pointer" id="shape1"/> <!-- 黑色图形:通过路径差集排除重叠区域 --> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z M0 0h133v67h-133v-67Z" fill="black" stroke="black" cursor="pointer" id="shape2" fill-rule="evenodd"/> </svg>
配合CSS旋转黑色图形:
#shape2 { transform: rotate(180deg); transform-origin: center; }
方法三:遮罩(mask)实现点击区域限制
用遮罩镂空黑色图形的重叠区域,仅保留可见部分响应点击:
<svg viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg"> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="#000eee" stroke="black" cursor="pointer" id="shape1"/> </svg> <svg class="rotate" viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg"> <defs> <mask id="maskShape2"> <rect width="100%" height="100%" fill="white"/> <!-- 用蓝色图形路径作为遮罩镂空部分 --> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="black"/> </mask> </defs> <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="currentColor" stroke="black" cursor="pointer" mask="url(#maskShape2)" pointer-events="visibleFill" id="shape2"/> </svg>
内容的提问来源于stack exchange,提问作者Pepszi
相关产品推荐
相关产品推荐

