Search code examples
javascriptkonvajs

How to set a default (or base) rotation on a transformer in KonvaJS?


Some context:

In my application, I have to display generated SVGs, which causes no issues.

But at some point, the back-end may (and will) return a rotated (modified) SVG, that I display in the canvas (I do know the actual rotation).

My issue:

My issue is that I cannot find a way to set the transformer base rotation.

For example, I know the image I inserted is a 90° rotated image, and I would like to have this rotation shown through the transformer when the image is selected (image has a base "canvas-rotation" of 0°, and the transformer a base "canvas-rotation" of 90°).

Summary:

To put it in another way, is it possible to offset the transformer rotation based on the attached node ?


Solution

  • There is no way to set "rotation offset" for Konva.Transformer. You have to use node's rotation for that. If you have an SVG image you can draw it into the offscreen canvas with rotation, and then use that canvas for Konva.Image.

    var imageObj = new Image();
    imageObj.onload = function() {
    
      const canvas = document.createElement('canvas');
      canvas.width = 200;
      canvas.height = 200;
    
      const ctx = canvas.getContext('2d');
      ctx.translate(canvas.width / 2, 0);
      ctx.rotate(Math.PI / 4);
      ctx.drawImage(imageObj, 0, 0, canvas.width * Math.cos(Math.PI / 4), canvas.height * Math.cos(Math.PI / 4))
    
      var yoda = new Konva.Image({
        x: 60,
        y: 60,
        image: canvas,
        draggable: true
      });
      // add the shape to the layer
      layer.add(yoda);
    
    
      const tr = new Konva.Transformer({
        node: yoda
      })
      layer.add(tr);
      layer.draw();
    };
    imageObj.src = 'https://konvajs.org/assets/yoda.jpg';
    

    https://jsbin.com/korigegupo/edit?html,js,output