Search code examples
javascriptvue.jscanvaskonvajs

How do you get used area of a KonvaJs Stage to pass as height/width properties into the toImage function?


I'm using KonvaJs 3.2.4 (though I probably could upgrade) and am trying to use the toImage function of the Stage Class. It looks as though toImage() by default only returns an image of the visible area of the stage, hence the config property to pass in the starting coordinates, and the height/width of area to return in the image.

My primary goal is to return an image of the stage that includes every child shape in that image (I'm using it as a cover image for printing, etc). Is there a way I can easily get the area of the Stage that is being used? I'm imagining an outerbounds of the used area. I currently keep all my shapes in one view layer, and before I run this toImage, I ungroup all the shapes so there are no nested arrays of children below the view Layer.

I tried to loop through all the children and use their x/y attributes to establish the minX, maxX, minY, maxY, but this runs into issues when a shape is rotated since the x/y coordinates can no longer be guaranteed to represent the inner/outer bounds of the shape. I do allow users to rotate using the standard Transformer.

Any guidance would be massively appreciated!


Solution

  • You can use node.getClientRect() to calculate total size of any Konva node. If you need to export a full image of the stage you can use this:

    stage.toImage({
      ...stage.getClientRect(),
      callback: img => {
        console.log(img);
      }
    })
    

    Demo: https://jsbin.com/behoyoyeda/1/edit?html,js,output