Upload svg2Base64.ts
Browse files
frontend/src/utils/svg2Base64.ts
CHANGED
@@ -48,8 +48,31 @@ const encode = (input: string) => {
|
|
48 |
}
|
49 |
|
50 |
export const svg2Base64 = (element: Element) => {
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
}
|
|
|
48 |
}
|
49 |
|
50 |
export const svg2Base64 = (element: Element) => {
|
51 |
+
try {
|
52 |
+
// 克隆元素以避免修改原始DOM
|
53 |
+
const clonedElement = element.cloneNode(true) as Element;
|
54 |
+
|
55 |
+
// 确保SVG有正确的命名空间
|
56 |
+
if (clonedElement.tagName.toLowerCase() === 'svg') {
|
57 |
+
clonedElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
58 |
+
clonedElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
|
59 |
+
}
|
60 |
+
|
61 |
+
const XMLS = new XMLSerializer();
|
62 |
+
const svg = XMLS.serializeToString(clonedElement);
|
63 |
+
|
64 |
+
if (!svg || svg.length === 0) {
|
65 |
+
throw new Error('SVG serialization returned empty string');
|
66 |
+
}
|
67 |
+
|
68 |
+
const encoded = encode(svg);
|
69 |
+
if (!encoded) {
|
70 |
+
throw new Error('Base64 encoding failed');
|
71 |
+
}
|
72 |
+
|
73 |
+
return PREFIX + encoded;
|
74 |
+
} catch (error) {
|
75 |
+
console.error('svg2Base64 failed:', error);
|
76 |
+
throw error;
|
77 |
+
}
|
78 |
}
|