javascript - KonvaJS, masking instead of clipFunc possible? - Stack Overflow

admin2025-04-20  0

I'm using konvajs and need some help!

Assume that I need an image that's draggable inside a plex shape.

I wonder if it's possible to use masking with Konva.Group instead of clipFunc OR a way to convert a masking image to canvas-clip-path and use it with clipFunc!

Like this: Masking draggable

I'm using konvajs and need some help!

Assume that I need an image that's draggable inside a plex shape.

I wonder if it's possible to use masking with Konva.Group instead of clipFunc OR a way to convert a masking image to canvas-clip-path and use it with clipFunc!

Like this: Masking draggable

Share Improve this question edited Jan 6, 2023 at 17:23 Paulo R. 15.6k4 gold badges33 silver badges42 bronze badges asked Jul 14, 2017 at 4:30 le namle nam 111 silver badge4 bronze badges 4
  • have you tried it so far? – Rohit Poudel Commented Jul 14, 2017 at 4:35
  • try??? idk how to do or what to try! – le nam Commented Jul 14, 2017 at 4:37
  • what you have done so far? – Rohit Poudel Commented Jul 14, 2017 at 4:38
  • i tried to masking canvas context by drawing use globalCompositeOperation = 'source-in', that doesn't work inside clipFunc (or at least idk how to get it work) – le nam Commented Jul 14, 2017 at 5:06
Add a ment  | 

1 Answer 1

Reset to default 6

By default Konva supports only simple clip with rectangle shape and clipping with clipFunc where you can describe required path.

https://konvajs.github.io/docs/clipping/Clipping_Function.html

In both cases, clipping is defined as canvas paths, and you can't define clip here as an image.

But you can draw directly into the canvas with custom Konva.Shape.

const girafe = new Image();
girafe.onload = () => {
  const img = new Image();
  img.onload = () => {
    const image = new Konva.Shape({
    sceneFunc: (ctx) => {
      ctx.drawImage(girafe, 0, 0);      
      ctx.globalCompositeOperation = 'source-in';
      ctx.drawImage(img, 0, 0);
    },
    // (!) important
    // for this case you need to define custom hit function
    hitFunc: (ctx) => {
      ctx.rect(0, 0, girafe.width, girafe.height);
      ctx.fillStrokeShape(image);
    },
    draggable: true
  });
  layer.add(image);
  layer.draw();
  };
  img.src = "http://i.imgur./kKjW3U4.png";

}
girafe.src = "http://i.imgur./fQX2P8S.png";

The output will be:

DEMO: http://jsbin./qahulidube/2/edit?js,output

Note: remember to define hitFunc because Konva hit detection will not work for such sceneFunc

Another two demos with other behaviors:

http://jsbin./huserozire/1/edit?js,output

http://jsbin./hawiricaqu/1/edit

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745127924a286536.html

最新回复(0)