Ahmed Ali
Ahmed Ali

Reputation: 1964

Add transformer to node when clicked - KonvaJs

I am creating an application and having some issue in adding transformer to node when clicked, I have done creating a .on function and getting node instance by evt.target but don't know how to attach transformer to node, There is a twist I have dynamically generated squares and I want to attach one transformer to one layer in the stage. As in many software you select the element in order to resize it.

  simpleText.on('dragmove', function(evt) {
    var shape = evt.target;
     //No instance of layer 
    console.log(evt.target);
    //If it returns any instance of layer then I would make new transformer and attach this node to it and to layer. 

});

Upvotes: 0

Views: 1215

Answers (1)

Mohamad Al
Mohamad Al

Reputation: 56

As shown in a KonvaJS Tutorial, this step is divided into 4 parts:

  1. Create a Transformer
  2. Add the Transformer to a Layer
  3. When you want to select change the Transformer Nodes, (Ex: transformer.nodes([shape]);) and when you want to clear. (Ex: transformer.nodes([]);)
  4. When you change the transformer, we have to Batch Draw the Layer. (Ex: layer.batchDraw();)

Here's a very basic example that you could expand upon to your likings:

const container = document.getElementById("container");

const stage = new Konva.Stage({
  container: container.id,
  width: container.offsetWidth,
  height: container.offsetHeight
});

const layer = new Konva.Layer();
stage.add(layer);

const rect = new Konva.Rect({
  x: 0,
  y: 0,
  width: 100,
  height: 50,
  fill: "green",
  stroke: "black",
  strokeWidth: 2,
  draggable: true
});
layer.add(rect);

const tr = new Konva.Transformer();
layer.add(tr);

stage.on("click tap", (e) => {
  // If we click on nothing clear the transformer and update the layer
  if (e.target === stage) {
    tr.nodes([]);
    layer.batchDraw();
    return;
  }
  
  // Add the selected element to the transformer and update the layer
  tr.nodes([e.target]);
  layer.batchDraw();
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Select Rectangle Demo</title>
    <script src="https://unpkg.com/konva@9.3.11/konva.min.js" integrity="sha384-0d42ivXJoYxiLyhtrHKXpBZi9mCV2dExQ09rtyeo8Vdi32FLT581cQmI3dtcG3QO" crossorigin="anonymous"></script>
    <style type="text/css">
      body, p {
        margin: 0;
      }

      #container {
        width: 80vw;
        height: 80vh;
        background-color: lightgray;
      }
  </style>
  </head>
  <body>
    <h1>Basic Select Rectangle Demo:</h1>
    <div id="container"></div>
    <p>Click on the rectangle to scale and rotate and click off when you're done</p>
  </body>
</html>

If you want to expand this further, I highly suggest looking at the KonvaJS Tutorial I mentioned earlier. Happy programming!

Upvotes: 0

Related Questions