perf: 优化导入自定义形状的svg viewBox

This commit is contained in:
zxc 2024-09-04 23:21:05 +08:00
parent 24ba7ea576
commit 3d7d1a7cc5
2 changed files with 32 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import { type ShapePoolItem, SHAPE_LIST, SHAPE_PATH_FORMULAS } from '@/configs/s
import useAddSlidesOrElements from '@/hooks/useAddSlidesOrElements' import useAddSlidesOrElements from '@/hooks/useAddSlidesOrElements'
import useSlideHandler from '@/hooks/useSlideHandler' import useSlideHandler from '@/hooks/useSlideHandler'
import message from '@/utils/message' import message from '@/utils/message'
import { getSvgPathRange } from '@/utils/svgPathParser'
import type { import type {
Slide, Slide,
TableCellStyle, TableCellStyle,
@ -304,7 +305,9 @@ export default () => {
if (el.shapType === 'custom') { if (el.shapType === 'custom') {
element.special = true element.special = true
element.path = el.path! element.path = el.path!
element.viewBox = [originWidth, originHeight]
const { maxX, maxY } = getSvgPathRange(element.path)
element.viewBox = [maxX || originWidth, maxY || originHeight]
} }
slide.elements.push(element) slide.elements.push(element)

View File

@ -207,4 +207,32 @@ export const toPoints = (d: string) => {
return points 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<typeof toPoints> export type SvgPoints = ReturnType<typeof toPoints>