Search code examples
javascriptcanvaskonvajskonva

How to clip several complex Images as Shapes in Konva.js, I just found only one complex Image solution in stackoverflow


hello @lavrton ,I found a similar problem in stackoverflow Link, your mentioned solution is a shape, but it can't render several shapes in the meantime. because the sceneFunc and hitFunc both use the whole canvas context, when I draw the new one, the old one will not show in the correct place, but in the counterpart of the context. How to handle it?

use the snippets below several times to build several nodes containing mask, but it meets the problem above

const mask = new Konva.Shape({
      id: KONVA_NODE_ID.MASK,
      x: 0.5 * width * (1 - range),
      y: 0.5 * height * (1 - range),
      width: width * range,
      height: height * range,
      sceneFunc: function (context, shape) {
        context.drawImage(imageObj, 0, 0, shape.width(), shape.height())
        context.globalCompositeOperation = 'source-in'
        context.drawImage(backObj, 0, 0, shape.width(), shape.height())
      },
      hitFunc: function (context, shape) {
        context.fillStrokeShape(shape)
      },
    })
group.add(mask)

Solution

  • If you want to have masking, it is better to do it outside Konva with an external canvas element and then just use that canvas for Konva.Image:

    const canvas = document.createElement('canvas');
    canvas.width = imageObj.width;
    canvas.height = imageObj.height;
    const ctx = canvas.getContext('2d');
    
    ctx.drawImage(imageObj, 0, 0)
    ctx.globalCompositeOperation = 'source-in'
    ctx.drawImage(backObj, 0, 0);
    
    const image = new Konva.Image({
      image: canvas
    });