Skip to main content

HTML5 Canvas Custom Filter Tutorial

How apply custom filter for Konva nodes?

This demo demonstrate how to use custom filters with Konva framework.

Filter is a function that have canvas ImageData as input and it should mutate it.

function Filter(imageData) {
// do something with image data
imageData.data[0] = 0;
}

For all available filters go to Filters Documentation.

Also take a look into Image Border Demo for custom filter example.

In this demo we will remove all transparency from the image.

import Konva from 'konva';

// create our custom filter
Konva.Filters.RemoveAlpha = function (imageData) {
  const data = imageData.data;
  for (let i = 0; i < data.length; i += 4) {
    data[i + 3] = 255; // set alpha to 1
  }
};

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.RemoveAlpha]);
  layer.draw();
};
imageObj.src = 'https://new.konvajs.org/assets/lion.png';
imageObj.crossOrigin = 'anonymous';