Is the Sharpness filter available in Konvajs, if it is there how to use that?

314 views Asked by At

https://konvajs.org/api/Konva.Filters.html

in this link the sharpness filter is not available

1

There are 1 answers

0
lavrton On

Konva doesn't have such a filter in its core. You have to implement it manually.

For that use case, you can write your own custom filter. See custom filters docs.

I tried to use that sharpen implementation: https://gist.github.com/mikecao/65d9fc92dc7197cb8a7c

// noprotect

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

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


function Sharpen(srcData) {
  const mix = 1;
  const w = srcData.width;
  const h = srcData.height;
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
    var x, sx, sy, r, g, b, a, dstOff, srcOff, wt, cx, cy, scy, scx,
        weights = [0, -1, 0, -1, 5, -1, 0, -1, 0],
        katet = Math.round(Math.sqrt(weights.length)),
        half = (katet * 0.5) | 0,
        dstData = ctx.createImageData(w, h),
        dstBuff = dstData.data,
        srcBuff = srcData.data,
        y = h;
  


    while (y--) {
        x = w;
        while (x--) {
            sy = y;
            sx = x;
            dstOff = (y * w + x) * 4;
            r = 0;
            g = 0;
            b = 0;
            a = 0;

            for (cy = 0; cy < katet; cy++) {
                for (cx = 0; cx < katet; cx++) {
                    scy = sy + cy - half;
                    scx = sx + cx - half;

                    if (scy >= 0 && scy < h && scx >= 0 && scx < w) {
                        srcOff = (scy * w + scx) * 4;
                        wt = weights[cy * katet + cx];

                        r += srcBuff[srcOff] * wt;
                        g += srcBuff[srcOff + 1] * wt;
                        b += srcBuff[srcOff + 2] * wt;
                        a += srcBuff[srcOff + 3] * wt;
                    }
                }
            }

            dstBuff[dstOff] = r * mix + srcBuff[dstOff] * (1 - mix);
            dstBuff[dstOff + 1] = g * mix + srcBuff[dstOff + 1] * (1 - mix);
            dstBuff[dstOff + 2] = b * mix + srcBuff[dstOff + 2] * (1 - mix);
            dstBuff[dstOff + 3] = srcBuff[dstOff + 3];
        }
    }
  for(var i = 0; i < dstData.data.length; i++) {
    srcData.data[i] = dstData.data[i];
  }
}

Konva.Image.fromURL('https://i.imgur.com/ktWThtZ.png', img => {
  img.setAttrs({filters: [Sharpen]});
  img.cache();
  layer.add(img);
  layer.draw();
});

Demo: https://jsbin.com/tejalusano/1/edit?html,js,output