js色相实现
色相(Hue)的实现方法
在JavaScript中,色相可以通过多种方式实现,包括使用CSS滤镜、Canvas操作或第三方库。以下是几种常见的实现方法:
使用CSS滤镜
通过CSS的filter属性可以调整元素的色相。hue-rotate函数接受一个角度值(0-360deg),对元素进行色相旋转。
.element {
filter: hue-rotate(90deg);
}
在JavaScript中动态修改色相:

const element = document.querySelector('.element');
element.style.filter = 'hue-rotate(180deg)';
使用Canvas修改色相
通过Canvas的getImageData和putImageData可以手动处理像素数据,实现色相调整。
function adjustHue(imageData, degrees) {
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const r = data[i], g = data[i+1], b = data[i+2];
const hsv = rgbToHsv(r, g, b);
hsv[0] = (hsv[0] + degrees / 360) % 1;
const rgb = hsvToRgb(hsv[0], hsv[1], hsv[2]);
data[i] = rgb[0]; data[i+1] = rgb[1]; data[i+2] = rgb[2];
}
return imageData;
}
使用第三方库
像chroma.js或tinycolor这样的库提供了色相调整的便捷方法。

import chroma from 'chroma-js';
const color = chroma('red').set('hsl.h', 120).hex();
RGB转HSV公式
手动实现色相调整需要RGB与HSV/HSL之间的转换公式:
RGB转HSV: $$ \begin{aligned} &\text{max} = \max(r, g, b), \text{min} = \min(r, g, b)\ &\text{h} = \begin{cases} 0 & \text{if max} = \text{min}\ 60 \times \frac{g - b}{\text{max} - \text{min}} + 0 & \text{if max} = r \text{ and } g \geq b\ 60 \times \frac{g - b}{\text{max} - \text{min}} + 360 & \text{if max} = r \text{ and } g < b\ 60 \times \frac{b - r}{\text{max} - \text{min}} + 120 & \text{if max} = g\ 60 \times \frac{r - g}{\text{max} - \text{min}} + 240 & \text{if max} = b \end{cases}\ &\text{s} = \begin{cases} 0 & \text{if max} = 0\ 1 - \frac{\text{min}}{\text{max}} & \text{otherwise} \end{cases}\ &\text{v} = \text{max} / 255 \end{aligned} $$
HSV转RGB: $$ \begin{aligned} &\text{h}' = \text{h} / 60, \text{c} = \text{v} \times \text{s}\ &\text{x} = \text{c} \times (1 - |(\text{h}' \mod 2) - 1|)\ &\text{m} = \text{v} - \text{c}\ &(\text{r}, \text{g}, \text{b}) = \begin{cases} (\text{c}, \text{x}, 0) & \text{if } 0 \leq \text{h}' < 1\ (\text{x}, \text{c}, 0) & \text{if } 1 \leq \text{h}' < 2\ (0, \text{c}, \text{x}) & \text{if } 2 \leq \text{h}' < 3\ (0, \text{x}, \text{c}) & \text{if } 3 \leq \text{h}' < 4\ (\text{x}, 0, \text{c}) & \text{if } 4 \leq \text{h}' < 5\ (\text{c}, 0, \text{x}) & \text{if } 5 \leq \text{h}' < 6 \end{cases}\ &(\text{r}, \text{g}, \text{b}) = ((\text{r} + \text{m}) \times 255, (\text{g} + \text{m}) \times 255, (\text{b} + \text{m}) \times 255) \end{aligned} $$
以上方法可以根据具体需求选择实现方式。CSS滤镜适合简单的前端效果,Canvas适合图像处理,而第三方库则提供了更高级的功能封装。






