跳到主要内容

HTML5 Canvas 图像色相、饱和度和明度滤镜教程

要对 Konva.Node 应用滤镜,必须先使用 cache() 函数缓存它。然后使用 filters() 函数应用滤镜。

要使用 Konva 更改图像的色相、饱和度和明度分量,可以使用 Konva.Filters.HSV

操作说明:滑动控件以更改 HSV 值。

有关全部可用滤镜,请参阅 滤镜文档

import Konva from 'konva';

const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const imageObj = new Image();
imageObj.onload = () => {
const image = new Konva.Image({
x: 50,
y: 50,
image: imageObj,
draggable: true,
});

layer.add(image);

image.cache();
image.filters([Konva.Filters.HSV]);

// create sliders
const createSlider = (label, min, max, defaultValue, property) => {
const container = document.createElement('div');
container.style.position = 'absolute';
container.style.left = '20px';

const text = document.createElement('span');
text.textContent = `${label}: `;
container.appendChild(text);

const slider = document.createElement('input');
slider.type = 'range';
slider.min = min;
slider.max = max;
slider.step = '0.1';
slider.value = defaultValue;
slider.style.width = '200px';

slider.addEventListener('input', (e) => {
const value = parseFloat(e.target.value);
image[property](value);
});

container.appendChild(slider);
return container;
};

const hueSlider = createSlider('Hue', -180, 180, 0, 'hue');
hueSlider.style.top = '20px';
document.body.appendChild(hueSlider);

const saturationSlider = createSlider('Saturation', -2, 10, 0, 'saturation');
saturationSlider.style.top = '45px';
document.body.appendChild(saturationSlider);

const value = createSlider('Value', -2, 2, 0, 'value');
value.style.top = '70px';
document.body.appendChild(value);
};
imageObj.src = 'https://konvajs.org/assets/darth-vader.jpg';
imageObj.crossOrigin = 'anonymous';