From 3d7d1a7cc5551c6f1d2c6c0f1679120f11e8a1bb Mon Sep 17 00:00:00 2001 From: zxc <1171051090@qq.com> Date: Wed, 4 Sep 2024 23:21:05 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=BD=A2=E7=8A=B6=E7=9A=84svg=20vie?= =?UTF-8?q?wBox?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useImport.ts | 5 ++++- src/utils/svgPathParser.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/hooks/useImport.ts b/src/hooks/useImport.ts index 03d5211b..46c6a802 100644 --- a/src/hooks/useImport.ts +++ b/src/hooks/useImport.ts @@ -8,6 +8,7 @@ import { type ShapePoolItem, SHAPE_LIST, SHAPE_PATH_FORMULAS } from '@/configs/s import useAddSlidesOrElements from '@/hooks/useAddSlidesOrElements' import useSlideHandler from '@/hooks/useSlideHandler' import message from '@/utils/message' +import { getSvgPathRange } from '@/utils/svgPathParser' import type { Slide, TableCellStyle, @@ -304,7 +305,9 @@ export default () => { if (el.shapType === 'custom') { element.special = true element.path = el.path! - element.viewBox = [originWidth, originHeight] + + const { maxX, maxY } = getSvgPathRange(element.path) + element.viewBox = [maxX || originWidth, maxY || originHeight] } slide.elements.push(element) diff --git a/src/utils/svgPathParser.ts b/src/utils/svgPathParser.ts index f7048089..4e3e5ac8 100644 --- a/src/utils/svgPathParser.ts +++ b/src/utils/svgPathParser.ts @@ -207,4 +207,32 @@ export const toPoints = (d: string) => { return points } +export const getSvgPathRange = (path: string) => { + try { + const pathData = new SVGPathData(path) + const xList = [] + const yList = [] + for (const item of pathData.commands) { + const x = ('x' in item) ? item.x : 0 + const y = ('y' in item) ? item.y : 0 + xList.push(x) + yList.push(y) + } + return { + minX: Math.min(...xList), + minY: Math.min(...yList), + maxX: Math.max(...xList), + maxY: Math.max(...yList), + } + } + catch { + return { + minX: 0, + minY: 0, + maxX: 0, + maxY: 0, + } + } +} + export type SvgPoints = ReturnType \ No newline at end of file