From f57859c38df51950f19ee6d7ff1a9c1fa616b953 Mon Sep 17 00:00:00 2001 From: Moritz Krause Date: Fri, 7 Feb 2020 03:03:37 +0100 Subject: [PATCH] feat(#20): add zoomToFit() function --- src/dtree.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/dtree.js b/src/dtree.js index 1f06a9c..f12a1f0 100644 --- a/src/dtree.js +++ b/src/dtree.js @@ -77,6 +77,27 @@ const dTree = { if (node) { _zoomTo(node.x, node.y, zoom, duration) } + }, + zoomToFit: function (duration = 500) { + const groupBounds = treeBuilder.g.node().getBBox() + const width = groupBounds.width + const height = groupBounds.height + const fullWidth = treeBuilder.svg.node().clientWidth + const fullHeight = treeBuilder.svg.node().clientHeight + const scale = 0.95 / Math.max(width / fullWidth, height / fullHeight) + + treeBuilder.svg + .transition() + .duration(duration) + .call( + treeBuilder.zoom.transform, + d3.zoomIdentity + .translate( + fullWidth / 2 - scale * (groupBounds.x + width / 2), + fullHeight / 2 - scale * (groupBounds.y + height / 2) + ) + .scale(scale) + ) } } },