Marling
Marling

Reputation: 89

How to remove resize sliders from an image in konvaJS

I made the functionality as in the example https://konvajs.org/docs/sandbox/Scale_Image_To_Fit.html. But I need to make that if the picture is out of focus, the sliders that need to be pulled disappear. How can i do this

const imgObj = new Image();
imgObj.onload = function() {
  Konva.Image.fromURL(url, function(img) {
    img.setAttrs({
      x: 170,
      y: 100,
      width: 185,
      height: 246,
      draggable: true,
      name: "image",
    });
    layer.add(img);
    layer.batchDraw();

    const tr = new Konva.Transformer({
      nodes: [img],
      keepRatio: false,
      flipEnabled: false,
      boundBoxFunc: function(oldBox, newBox) {
        if (
          Math.abs(newBox.width) < 10 ||
          Math.abs(newBox.height) < 10
        ) {
          return oldBox;
        }
        return newBox;
      },
    });

    layer.add(tr);

    img.on("transform", function() {
      img.setAttrs({
        scaleX: 1,
        scaleY: 1,
        width: img.width() * img.scaleX(),
        height: img.height() * img.scaleY(),
      });
      applyCrop(img.getAttr("lastCropUsed"));
    });
  });
};
imgObj.src = url;

Upvotes: 1

Views: 69

Answers (1)

lavrton
lavrton

Reputation: 20308

You can use click on even on the stage to hide/show transformer:

    // Event listener for image click
    img.on('click', function() {
      tr.nodes([img]); // Attach transformer to the image
    });

    // Event listener for stage click
    stage.on('click', function(e) {
      // Check if the click is on empty space
      if (e.target === stage) {
        tr.nodes([]);    // Hide the transformer
      }
    });

Upvotes: 1

Related Questions