不使用CSS滤镜改变图像颜色



我想用CSS改变图片的颜色。

问题是它不能与过滤器,我通常使用以下代码:

filter: hue-rotate(339deg) brightness(1);

它可以工作,但如果图像是黑色的,它就不起作用,如果它有颜色,它只显示X颜色的变化。我希望能够改变所有的颜色。

您可以通过以下方式对图像应用颜色滤镜:

  • 定位一个部分透明背景的图层(使用rgba())
  • 演示:

const layer = document.querySelector('.layer');
input.addEventListener('input', function() {
  const r = parseInt(input.value.substr(1, 2), 16)
  const g = parseInt(input.value.substr(3, 2), 16)
  const b = parseInt(input.value.substr(5, 2), 16)
  layer.style.backgroundColor = `rgb(${r}, ${g}, ${b}, 0.9)`;
})
.container {
  position: relative;
  width:fit-content;
}
.layer {
  position: absolute;
  top: 0;
  left: 0;
  height:100%;
  width:100%;
}
.img {
  height: 100px;
  width: 100px;
  background: url("https://i.imgur.com/0etSSYl.png");
  background-size: cover;
}
<div class="container">
  <div class="layer"></div>
  <div class="img"></div>
</div>
<hr>
<input type="color" id="input">
<-- apply color filter

@black-icon: invert(0%) sepia(0%) saturate(0%) hue-rotate(0deg) brightness(0%)
  contrast(100%);
@white-icon: invert(100%) sepia(0%) saturate(0%) hue-rotate(0deg)
  brightness(100%) contrast(100%);
@green-icon: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg)
  brightness(118%) contrast(119%);
@red-icon: invert(15%) sepia(84%) saturate(6546%) hue-rotate(358deg)
  brightness(92%) contrast(120%);
@blue-icon: invert(8%) sepia(99%) saturate(7172%) hue-rotate(248deg)
  brightness(102%) contrast(142%);
@purple-icon: invert(28%) sepia(75%) saturate(2208%) hue-rotate(290deg)
  brightness(105%) contrast(125%);
@yellow-icon: invert(50%) sepia(100%) saturate(3532%) hue-rotate(58deg)
  brightness(115%) contrast(135%);
@orange-icon: invert(55%) sepia(85%) saturate(4321%) hue-rotate(28deg)
  brightness(110%) contrast(130%);
@pink-icon: invert(35%) sepia(88%) saturate(2694%) hue-rotate(320deg)
  brightness(102%) contrast(130%);
@teal-icon: invert(10%) sepia(94%) saturate(6280%) hue-rotate(168deg)
  brightness(107%) contrast(140%);
@gray-icon: invert(40%) sepia(70%) saturate(1814%) hue-rotate(12deg)
  brightness(120%) contrast(115%);
@violet-icon: invert(20%) sepia(85%) saturate(3073%) hue-rotate(258deg)
  brightness(108%) contrast(130%);
@cyan-icon: invert(5%) sepia(98%) saturate(6827%) hue-rotate(198deg)
  brightness(104%) contrast(145%);
@lime-icon: invert(45%) sepia(92%) saturate(5040%) hue-rotate(88deg)
  brightness(113%) contrast(135%);
@indigo-icon: invert(15%) sepia(96%) saturate(4368%) hue-rotate(178deg)
  brightness(106%) contrast(140%);
@brown-icon: invert(25%) sepia(80%) saturate(2422%) hue-rotate(38deg)
  brightness(118%) contrast(125%);
@maroon-icon: invert(8%) sepia(90%) saturate(5935%) hue-rotate(338deg)
  brightness(98%) contrast(140%);
@olive-icon: invert(30%) sepia(75%) saturate(3786%) hue-rotate(68deg)
  brightness(112%) contrast(130%);

最新更新