2

While using konva I am using a button to add a shape multiple times on to my Stage using something similar to

      document.getElementById('Rect').addEventListener( "click" , function () {

        let layer = new Konva.Layer();

        let item = new Konva.Rect({
          x: 20,
          y: 20,
          width: 100,
          height: 50,
          fill: 'green',
          stroke: 'black',
          strokeWidth: 4,
          draggable: true,
        });

This appends a rectangle shape, if clicked multiple times it also appends extra shapes I want to provide user with an option of deleting a particular shape that he wishes to delete with a button. I tried to use context Menu tutorial available at Konva Tutorials but when implementing the delete function available there

        document.getElementById('delete-button').addEventListener('click', () => {

          currentShape.destroy();

          layer.draw();
        });

It is unable to delete the transformer layer added to the shape

        document.getElementById('delete-button').addEventListener('click', () => {
          tr.detach();
          currentShape.destroy();

          layer.draw();
        });

I tried to detach the transformer / hide it but it removes it from all available instances of the shape

How can I solve this problem, Thanks a lot !!

Akshat Tulsani
  • 101
  • 1
  • 8
  • Can you make a demo? As I can see you are adding a new layer on every button click. I am not sure that is the correct behavior. Also, you need to redraw layer on which the transformer is placed. – lavrton Jun 15 '20 at 12:38
  • Hey thank you for your reply, Link for demo: https://codepen.io/Tulsani/pen/OJMRQPr Here if I try to add two rectangles using the button on to the stage and delete one the transformer for the remaining one also is removed. Thank you for the help !! – Akshat Tulsani Jun 16 '20 at 06:42

1 Answers1

5

You are adding a new click event listener for the "delete" button INSIDE click event of "add" button. That means every time you click on "delete" ALL listeners will be triggered. That removes all transformers.

Instead, you need just add a click listener once and find active Transformer manually to delete it.

document.getElementById('delete-button').addEventListener('click', () => {
  const tr = layer.find('Transformer').toArray().find(tr => tr.nodes()[0] === currentShape);
  tr.destroy();
  currentShape.destroy();
  layer.draw();
});

https://codepen.io/lavrton/pen/VweKqrp?editors=0010

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • Hi, really thankful for your help, I wanted a little more help how can i make this functional for multiple shapes. Here when use it for deleting a rectangle it works but when i also add an 'add circle' button, it is unable to delete the circle but works just fine for the rectangle. Thank you !! Demo for the same : https://codepen.io/Tulsani/pen/JjGRVZK – Akshat Tulsani Jun 16 '20 at 17:26