Skip to main content

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

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

要在 Konva 中更改图像的色相、饱和度和亮度组件,我们可以使用 Konva.Filters.HSL

说明:滑动控制以更改 HSL 值。

有关所有可用滤镜,请访问 滤镜文档

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.HSL]);
  
  // 创建滑动条
  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('色相', -180, 180, 0, 'hue');
  hueSlider.style.top = '20px';
  document.body.appendChild(hueSlider);

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

  const luminanceSlider = createSlider('亮度', -2, 2, 0, 'luminance');
  luminanceSlider.style.top = '70px';
  document.body.appendChild(luminanceSlider);
};
imageObj.src = 'https://konvajs.org/assets/lion.png';
imageObj.crossOrigin = 'anonymous';