Render SVG as base64 image and improve scaling

This commit is contained in:
ema
2025-06-30 07:22:03 +08:00
parent 0dc8c03446
commit 0a8039d962
2 changed files with 40 additions and 11 deletions

View File

@@ -19,9 +19,12 @@
user-select: none;
}
#svgWrapper {
#svgWrapper img {
transform-origin: center center;
transition: transform 0.1s ease-out;
display: block;
max-width: 100%;
max-height: 100%;
}
</style>
</head>

View File

@@ -1,14 +1,44 @@
(async function () {
function encodeSvgToBase64(svg) {
const utf8Bytes = new TextEncoder().encode(svg);
let binary = '';
for (const byte of utf8Bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
function fixSvgSize(svg) {
const viewBoxMatch = svg.match(/viewBox\s*=\s*["']?([\d\s\.]+)["']/i);
if (!viewBoxMatch) return svg;
const parts = viewBoxMatch[1].trim().split(/\s+/);
if (parts.length !== 4) return svg;
const width = parseFloat(parts[2]);
const height = parseFloat(parts[3]);
if (/width\s*=/.test(svg) || /height\s*=/.test(svg)) {
return svg;
}
return svg.replace(
/<svg([^>]*)>/i,
`<svg width="${width}" height="${height}"$1>`
);
}
const wrapper = document.getElementById("svgWrapper");
const svgString = await chrome.webview.hostObjects.external.GetSvgContent();
wrapper.innerHTML = svgString;
const base64 = encodeSvgToBase64(fixSvgSize(svgString));
const img = new Image();
img.src = `data:image/svg+xml;base64,${base64}`;
img.style.transform = "scale(1)";
let scale = 1;
function updateTransform() {
wrapper.style.transform = `scale(${scale})`;
img.style.transform = `scale(${scale})`;
}
document.addEventListener("wheel", (e) => {
@@ -16,12 +46,7 @@
const scaleFactor = 1.2;
if (e.deltaY < 0) {
scale *= scaleFactor;
} else {
scale /= scaleFactor;
}
scale *= (e.deltaY < 0 ? scaleFactor : 1 / scaleFactor);
updateTransform();
}, { passive: false });
@@ -31,5 +56,6 @@
updateTransform();
});
wrapper.appendChild(img);
updateTransform();
})();