首页 > 解决方案 > CSS背景混合模式黑色蒙版

问题描述

使用 css background-blend-mode 我正在尝试设置一个蒙版,其中第一个背景图像白色部分在最后一个上应用黑色蒙版。

这是一个代码示例,显示了我卡在哪里:https ://codepen.io/BackNight/pen/YzQgyjo

.container {
  background-color: black;
  width: 200px;
  height: 200px;
  background-image: url('data:image/svg+xml,%3Csvg width="100" height="100" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg"%3E%3Cg fill="%23fff" fill-opacity="1" fill-rule="evenodd"%3E%3Cpath d="M0 40L40 0H20L0 20M40 40V20L20 40"/%3E%3C/g%3E%3C/svg%3E'), radial-gradient(closest-side, #1499ff calc(100% - 1px), transparent);
  background-size: auto, 75px 75px;
  background-repeat: no-repeat;
  background-position: right bottom, right 40px bottom;
  background-blend-mode: difference;
}

我只能用“差异”模式获得橙色,我只需要它是黑色的:

在此处输入图像描述

给你一个我想要的最终结果的例子:

在此处输入图像描述

标签: cssbackground-blend-mode

解决方案


您可以做的不是依赖混合模式,它使您几乎无法控制颜色,而是实际上.container用一个伪元素覆盖您,该元素具有您想要的替代调色板中的 SVG(在这种情况下,背景的#1499ff和一个填充的#000000

然后,您可以使用clip-path隐藏叠加层的其余部分,并使用 CSS 属性来控制叠加层的位置(如果需要)。请参见下面的示例:

// Optional JS to demonstrate an interactable mask
document.querySelector('.container').addEventListener('mousemove', (e) => {
  e.target.style.setProperty('--circleX', `${e.clientX}px`);
  e.target.style.setProperty('--circleY', `${e.clientY}px`);
});
.container {
  background-color: black;
  width: 200px;
  height: 200px;
  background-image: url('data:image/svg+xml,%3Csvg width="100" height="100" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg"%3E%3Cg fill="%23fff" fill-opacity="1" fill-rule="evenodd"%3E%3Cpath d="M0 40L40 0H20L0 20M40 40V20L20 40"/%3E%3C/g%3E%3C/svg%3E');
  position: relative;
}

.container,
.container::after {
  background-size: auto;
  background-repeat: no-repeat;
  background-position: right bottom;
}

.container::after {
  position: absolute;
  cursor: pointer;
  content: '';
  inset: 0;
  background-color: #1499ff;
  background-image: url('data:image/svg+xml,%3Csvg width="100" height="100" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg"%3E%3Cg fill="%23000" fill-opacity="1" fill-rule="evenodd"%3E%3Cpath d="M0 40L40 0H20L0 20M40 40V20L20 40"/%3E%3C/g%3E%3C/svg%3E');
  clip-path: circle(50px at var(--circleX, 50%) var(--circleY, 50%));
}
<div class="container">
</div>


推荐阅读