如何合并SVG遮罩?实现双遮罩白色区域可见效果
解决SVG两个遮罩合并显示白色区域的问题
你的代码存在两个关键问题导致无法正常工作:
mask属性只能引用<mask>元素,不能直接用<filter>的ID,原代码里给rect设置mask="url(#combinedMask)"是无效的feComposite不能直接把mask元素作为输入源,需要先通过feImage加载mask的内容
下面提供两种可行的解决方案:
方案一:直接在单个遮罩中组合图形(最简便)
既然要显示两个遮罩的白色区域,直接在一个mask里把两个白色矩形放进去,背景用黑色填充即可,不需要用到filter:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <mask id="combinedMask" x="0" y="0" width="200" height="200"> <!-- 黑色背景 --> <rect x="0" y="0" width="200" height="200" fill="black"/> <!-- 第一个遮罩的白色区域 --> <rect x="0" y="0" width="100" height="100" fill="white"/> <!-- 第二个遮罩的白色区域 --> <rect x="100" y="100" width="100" height="100" fill="white"/> </mask> </defs> <rect x="0" y="0" width="200" height="200" fill="red" mask="url(#combinedMask)"/> </svg>
方案二:用feComposite实现遮罩合并(符合你原本的思路)
如果一定要用feComposite,需要先把两个mask的内容通过feImage导入到filter中,然后用operator="over"合并,最后把filter的结果作为新mask的内容:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <mask id="mask1" x="0" y="0" width="200" height="200"> <rect x="0" y="0" width="200" height="200" fill="black"/> <rect x="0" y="0" width="100" height="100" fill="white"/> </mask> <mask id="mask2" x="0" y="0" width="200" height="200"> <rect x="0" y="0" width="200" height="200" fill="black"/> <rect x="100" y="100" width="100" height="100" fill="white"/> </mask> <filter id="compositeFilter"> <!-- 加载第一个遮罩的内容 --> <feImage href="#mask1" result="mask1"/> <!-- 加载第二个遮罩的内容 --> <feImage href="#mask2" result="mask2"/> <!-- 合并两个遮罩,over表示叠加显示两者的白色区域 --> <feComposite in="mask1" in2="mask2" operator="over"/> </filter> <!-- 使用filter的结果作为新的遮罩 --> <mask id="combinedMask" x="0" y="0" width="200" height="200"> <rect x="0" y="0" width="200" height="200" filter="url(#compositeFilter)"/> </mask> </defs> <rect x="0" y="0" width="200" height="200" fill="red" mask="url(#combinedMask)"/> </svg>
两种方案都能实现你要的效果:红色背景上显示左上角和右下角两个对应区域的红色方块。
内容的提问来源于stack exchange,提问作者Ron
相关产品推荐
相关产品推荐

