0

I have a canvas which displays some SVG paths. I've drawn these using KonvaJs. Users should be able to click on any of these paths and zoom in on it. After clicking a path, the canvas should zoom to the point where the path fits the full size of the canvas. See this JsFiddle. (The paths will be imported from another source).

I know you can scale a layer like this:

layer.scale({ 
    x : 2,
    y : 2
});

But I don't know what x and y value it needs to get the right scale.

So, my question: How to zoom/scale a path to fit it's container, using KonvaJs?

I hope you know what I mean. If not, AmCharts' Maps does the exact thing I want to accomplish. When you click on a country, the canvas zooms in on it. The zoom animation would be nice to have, but is not a requirement. I'm not using AmCharts because it doesn't fit (the rest of) my needs.

Note: I started using KonvaJs because I've used KineticJs before. As I understand, KineticJs is not maintained anymore, but KonvaJs is a fork of it (correct me if I'm wrong). If you know of a better library to do this, please let me know.

RobinvdA
  • 1,313
  • 2
  • 13
  • 28

1 Answers1

1

You can use nice function getClientRect() to detect bounding box of any core shape.

    var rect = e.target.getClientRect();
    var scale = Math.max(
        stage.width() / rect.width,
      stage.height() / rect.height
    );
    layer.x(-rect.x * scale);
    layer.y(-rect.y * scale);
    layer.scale({x: scale, y: scale});

DEMO: https://jsfiddle.net/g06utup0/1/

Note: while making demo I found bug in Path.getClientRect() calculation. So you have to use last version from repo.

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • Ah that's the function i need, thanks! I changed `Math.max` to `Math.min` so when scaling the entire path is visible: https://jsfiddle.net/g06utup0/2/ What bug did you find in `getClientRect()`? – RobinvdA Feb 05 '16 at 08:29
  • @lavrton, Hello! I'm using your fiddle as an example, but I get an unexpected result, can you take a look? https://jsfiddle.net/3qu1qmjs (`getClientRect` returns wrong rect) – aush May 06 '16 at 12:07