hue-rotate()

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

hue-rotate() CSS 函数用于旋转元素及其内容的色相。其结果是 <filter-function>

注意: hue-rotate() 被指定为对 RGB 颜色执行的矩阵运算。它实际上不会将颜色转换为 HSL 模型,因为 HSL 是一种非线性操作。因此,它可能无法保持原始颜色的饱和度或亮度,尤其是对于饱和度较高的颜色。

试一试

filter: hue-rotate(0);
filter: hue-rotate(90deg);
filter: hue-rotate(-0.25turn);
filter: hue-rotate(3.142rad);
<section id="default-example">
  <img
    class="transition-all"
    id="example-element"
    src="/shared-assets/images/examples/firefox-logo.svg"
    width="200" />
</section>

语法

css
hue-rotate(angle)

angle 可选

输入样本的色相相对变化,指定为 <angle>。值为 0deg 时,输入保持不变。正色相旋转会增加色相值,而负色相旋转会减小色相值。插值的初始值为 0。没有最小值或最大值。对于 hue-rotate(Ndeg),值超过 360deg 的效果计算为 N 模 360。默认值为 0deg

<angle> CSS 数据类型表示以度、梯度、弧度或圈数表示的角度值。以下是等效的:

css
hue-rotate(-180deg)
hue-rotate(540deg)
hue-rotate(200grad)
hue-rotate(3.14159rad)
hue-rotate(0.5turn)

正式语法

<hue-rotate()> = 
hue-rotate( [ <angle> | <zero> ]? )

示例

使用 backdrop-filter 属性

此示例通过 backdrop-filter CSS 属性将 hue-rotate() 滤镜应用于段落,从而将 <p> 后面的区域进行色相偏移。

css
.container {
  background: url("/shared-assets/images/examples/listen_to_black_women.jpg")
    no-repeat left / contain #011296;
}
p {
  backdrop-filter: hue-rotate(240deg);
  text-shadow: 2px 2px #011296;
}

使用 filter 属性

此示例通过 filter CSS 属性应用 hue-rotate() 滤镜,将色相偏移应用于整个元素,包括内容、边框和背景图像。

css
p {
  filter: hue-rotate(-60deg);
  text-shadow: 2px 2px blue;
  background-color: magenta;
  color: goldenrod;
  border: 1em solid rebeccapurple;
  box-shadow:
    inset -5px -5px red,
    5px 5px yellow;
}

使用 url() 和 SVG hue-rotate 滤镜

SVG <filter> 元素用于定义自定义滤镜效果,然后可以通过 id 进行引用。<filter><feColorMatrix> 原始类型 hueRotate 提供了相同的效果。鉴于以下内容:

html
<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 220 220"
  color-interpolation-filters="sRGB"
  height="220"
  width="220">
  <filter id="hue-rotate">
    <feColorMatrix type="hueRotate" values="90" />
  </filter>
</svg>

这些值产生相同的结果:

css
filter: hue-rotate(90deg); /* 90deg rotation */
filter: url("#hue-rotate"); /* with embedded SVG */
filter: url("folder/fileName.svg#hue-rotate"); /* external svg filter definition */

此示例显示了三张图像:应用了 hue-rotate() 滤镜函数的图像、应用了等效 url() 滤镜的图像,以及原始图像用于比较。

hue-rotate() 不保留饱和度或亮度

下图比较了两个从红色开始的颜色渐变:第一个使用 hue-rotate() 生成,第二个使用实际的 HSL 颜色值。请注意 hue-rotate() 渐变在中间部分显示出明显的饱和度和亮度差异。

html
<div>
  <p>Using <code>hue-rotate()</code></p>
  <div id="hue-rotate"></div>
</div>
<div>
  <p>Using <code>hsl()</code></p>
  <div id="hsl"></div>
</div>
js
const hueRotate = document.getElementById("hue-rotate");
const hsl = document.getElementById("hsl");

for (let i = 0; i < 360; i++) {
  const div1 = document.createElement("div");
  div1.style.backgroundColor = `hsl(${i}, 100%, 50%)`;
  hsl.appendChild(div1);

  const div2 = document.createElement("div");
  div2.style.backgroundColor = "red";
  div2.style.filter = `hue-rotate(${i}deg)`;
  hueRotate.appendChild(div2);
}

规范

规范
滤镜效果模块第 1 级
# funcdef-filter-hue-rotate

浏览器兼容性

另见