2

is there any way to add a shape in KonvaJS which draws outside of it's boundries? Basically a "hole" in the layer, so that I can highlight a spot in the canvas by making everything around a circle darker (black with low opacity).

Any help is much appreciated!

Cheers

Edit: Here is an image of what I mean (I'm not allowed to embed it yet): https://i.stack.imgur.com/2yve2.jpg

I was hoping there might be something like this:

Konva.Circle({
  x: 100,
  y: 100,
  radius: 50,
  opacity: 0.3,
  fill: 'black',
  inverted: true
})

and this would then in turn "not draw" a circle, but everything around it would then take the given attributes. In this case it would all be darkend a bit besides the circle.

Daniel.S
  • 23
  • 7

1 Answers1

3

You can do this with a custom shape:

const shape = new Konva.Shape({
  width: stage.width(),
  height: stage.height(),
  // what is color of background ?
  fill: 'rgba(0,0,0,0.2)',
  sceneFunc: (ctx, shape) => {
    // draw background
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(shape.width(), 0);
    ctx.lineTo(shape.width(), shape.height());
    ctx.lineTo(0, shape.height());
    ctx.lineTo(0, 0);

    // now cut circle from the background
    // we can do this by useing arc
    const x = 200;
    const y = 200;
    const radius = 10;
    // but it must be counter-clockwise
    // so the last argument true is very important here
    ctx.arc(200, 200, 100, 0, Math.PI * 2, true);
    ctx.fillStrokeShape(shape);
  },

  // remove shape from hit graph, so it is not visible for events
  listening: false
});

Demo: https://jsbin.com/tevejujafi/3/edit?html,js,output

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • This seems to be pretty much exactly what I need. I don't quite understand how the cutting of the circle is working here. You are drawing a rectangle from corner to corner and then you just draw a circle. But how does the shape know that the circle's inside doesn't belong to the shape? Is it the fillStrokeShape method, which handles this? – Daniel.S Jan 07 '19 at 15:10
  • 1
    Is this to do with 'non-zero winding' for fill ? See [wikipedia explanation here](https://secure.wikimedia.org/wikipedia/en/wiki/Nonzero-rule). – Vanquished Wombat Jan 08 '19 at 07:45
  • Is there a way to remove a different shape instead of an `arc`? – ruwan800 Jan 27 '22 at 04:33