Browse Source

fix: 完善脑图缩放效果

zhupei 1 year ago
parent
commit
a9558d1e13
1 changed files with 22 additions and 20 deletions
  1. 22 20
      src/components/MindMap.vue

+ 22 - 20
src/components/MindMap.vue

@@ -11,6 +11,8 @@ import * as markmap from 'markmap-view';
 import { loadJS, loadCSS } from 'markmap-common';
 import { Transformer } from 'markmap-lib';
 
+import { zoomTransform } from 'd3';
+
 const transformer = new Transformer();
 const { scripts, styles } = transformer.getAssets();
 loadCSS(styles);
@@ -357,11 +359,13 @@ function updateIconProgress(item) {
 }
 const getCenter = () => {
   const svg = svgRef.value;
-  console.dir(svg);
+
   const width = svg.clientWidth;
   const height = svg.clientHeight;
 
   return {
+    w: width,
+    h: height,
     x: width / 2,
     y: height / 2
   };
@@ -387,30 +391,28 @@ const getCurrentZoomScale = () => {
 
 // 应用缩放
 const applyZoom = (scaleFactor) => {
-  const center = getCenter(); // 获取视图中心点
-  // 计算新的变换矩阵:缩放 + 平移
-  const newTransform = `scale(${scaleFactor}) translate(${center.x * scaleFactor}, ${center.y * scaleFactor})`;
-  // console.log(newTransform);
-  // 将新的变换应用到 Markmap
-  mark_map.handleZoom({ transform: newTransform });
-  // mark_map.rescale(scaleFactor);
+  const svg = svgRef.value; // 获取 SVG 元素
+  const ele_g = svg.childNodes[1];
+  const transform_attr = ele_g.getAttribute('transform');
+  const scaleMatch = transform_attr.match(/scale\(([^)]+)\)/); // 匹配 scale() 中的值
+  const scale_value = scaleMatch[1] / 1;
+  const arr = transform_attr.split(' ');
+  const transform_value = `${arr[0]} scale(${scale_value + scaleFactor})`;
+  ele_g.setAttribute('transform', transform_value);
+
+  // const svg = svgRef.value; // 获取 SVG 元素
+  // const transform = zoomTransform(svg);
+  // const newTransform = transform.scale(scaleFactor);
+  // mark_map.handleZoom({ transform: newTransform });
 };
-//
+
 const zoomIn = () => {
-  let scale = getCurrentZoomScale();
-  // console.log(scale);
-  scale = scale + 0.1;
-  applyZoom(scale);
+  applyZoom(0.1);
 };
 const zoomOut = () => {
-  let scale = getCurrentZoomScale();
-  // console.log(scale);
-  if (scale <= 0.1) {
-    return;
-  }
-  scale = scale - 0.1;
-  applyZoom(scale);
+  applyZoom(-0.1);
 };
+
 const zoomReset = () => {
   mark_map.fit();
 };