如何对图像使用 CSS 遮罩?

How to use a CSS mask with an image?

我正在尝试在图像上添加渐变蒙版,但它不起作用

     <div className="first-section">
     <img src={BgPic} alt="Bg-pic" className="bg-pic" />
     </div>
 .bg-pic{
     width:100%;

     mask-image:linear-gradient(180deg, #000000 0%, #380A46 100%) 0% 0% no-repeat padding-box;
  }

面膜的正确使用方法是什么:

要了解如何正确使用掩码,您需要首先参考 the specification

中详述的 mask-mode

The mask-mode property indicates whether the <mask-reference> is treated as luminance mask or alpha mask. (See Mask processing.)

 <masking-mode> = alpha | luminance | match-source

默认值为match-source,使用渐变时,您将拥有:

If the <mask-reference> of the mask-image property is of type <image> the alpha values of the mask layer image should be used as the mask values.

渐变是图像:https://drafts.csswg.org/css-images-3/#typedef-image

那么如果你参考 the mask processing 你会读到:

The first and simplest method of calculating the mask values is to use the alpha channel of the mask image. In this case the mask value at a given point is simply the value of the alpha channel at that point. The color channels do not contribute to the mask value.

所以使用你的渐变你将什么都没有,因为你的颜色的 alpha 通道等于 1

要么考虑透明(或半透明)颜色

img{
  -webkit-mask: linear-gradient(180deg, transparent 0%, #380A46 100%) 0% 0% no-repeat padding-box;
          mask: linear-gradient(180deg, transparent 0%, #380A46 100%) 0% 0% no-repeat padding-box;
}
<img src="https://picsum.photos/id/1/300/200" >

或更改模式(仅适用于 Firefox)

img{
  -webkit-mask: linear-gradient(180deg, #000000 0%, #380A46 100%) 0% 0% no-repeat padding-box;
          mask: linear-gradient(180deg, #000000 0%, #380A46 100%) 0% 0% no-repeat padding-box;
          mask-mode:luminance;
}
<img src="https://picsum.photos/id/1/300/200" >

请注意,我使用的是 mask 而不是 mask-image,这是您在这里需要的,因为您正在考虑其他值,例如 mask-repeatmask-positionmask-clip 所以手写 属性 是这里需要的。