Skip to main content

HTML5 Canvas Enhance Image Filter Tutorial

To apply filter to an Konva.Image, we have to cache it first with cache() function. Then apply filter with filters() function.

To enhance an image with Konva, we can use the Konva.Filters.Enhance filter and set the enhance amount with the enhance property.

Instructions: Slide the control to adjust the enhance value.

For all available filters go to Filters Documentation.

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.Enhance]);
  image.enhance(0.4);

  const slider = document.createElement('input');
  slider.type = 'range';
  slider.min = '-1';
  slider.max = '1';
  slider.step = '0.1';
  slider.value = image.enhance();

  slider.style.position = 'absolute';
  slider.style.top = '20px';
  slider.style.left = '20px';

  slider.addEventListener('input', (e) => {
    const value = parseFloat(e.target.value);
    image.enhance(value);
    layer.batchDraw();
  });

  document.body.appendChild(slider);
};
imageObj.src = 'https://new.konvajs.org/assets/lion.png';
imageObj.crossOrigin = 'anonymous';