Files
faunosteo/src/pdf/render/svgToPng.ts
T
Bastien Chanot bbdc0e851a chore: remove dead code and duplicate logic
- drop unused assertNever, canvg dependency (never imported),
  readonly re-export shim in VertebraPicker, stale equine named export
- unexport validateBoneElement (internal only)
- getBoneIdFromEvent now delegates to getAnnotatedElement (dup walk-up)
- rasterizeSvg: drop ignored _scale param (2 call sites + tests)
- extract byte-identical word-wrap into pdf/render/text.ts
- extract mergeBones helper in EditorRoute (block duplicated twice)
- fix stale canvg comment in observationPage
Checks: typecheck, lint, 174/174 tests, build all green
2026-07-12 04:47:54 +02:00

122 lines
4.1 KiB
TypeScript

const TARGET_WIDTH = 1200
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
function startsWithPngSignature(bytes: Uint8Array): boolean {
if (bytes.length < PNG_SIGNATURE.length) return false
for (let i = 0; i < PNG_SIGNATURE.length; i += 1) {
if (bytes[i] !== PNG_SIGNATURE[i]) return false
}
return true
}
function ensureSvgAttributes(
svgString: string,
widthPx: number,
heightPx: number,
): string {
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const root = doc.documentElement
if (root.namespaceURI !== 'http://www.w3.org/2000/svg') {
// Some serializers strip xmlns; force the SVG namespace so
// browsers will rasterize the blob URL as an image.
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
}
if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx))
if (!root.getAttribute('height')) root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
function readViewBox(svgString: string): {
widthPx: number
heightPx: number
} {
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const vb = (doc.documentElement.getAttribute('viewBox') ?? '0 0 1000 600')
.split(/\s+/)
.map(Number)
const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6
const widthPx = Math.max(1, Math.round(TARGET_WIDTH))
const heightPx = Math.max(1, Math.round(ratio * widthPx))
return { widthPx, heightPx }
}
async function rasterizeWithImageElement(
svgString: string,
widthPx: number,
heightPx: number,
): Promise<HTMLCanvasElement> {
const normalized = ensureSvgAttributes(svgString, widthPx, heightPx)
const svgBlob = new Blob([normalized], {
type: 'image/svg+xml;charset=utf-8',
})
const url = URL.createObjectURL(svgBlob)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
try {
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve()
img.onerror = () =>
reject(new Error('Browser failed to render the SVG into an Image'))
img.src = url
})
} finally {
// The Blob URL is single-use — release it once the Image has loaded
// (or failed).
URL.revokeObjectURL(url)
}
const canvas = document.createElement('canvas')
canvas.width = widthPx
canvas.height = heightPx
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, widthPx, heightPx)
ctx.drawImage(img, 0, 0, widthPx, heightPx)
return canvas
}
async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> {
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/png')
})
if (blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
if (startsWithPngSignature(bytes)) return bytes
}
const dataUrl = canvas.toDataURL('image/png')
if (!dataUrl.startsWith('data:image/png')) {
throw new Error(
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
)
}
const comma = dataUrl.indexOf(',')
if (comma < 0) {
throw new Error('canvas.toDataURL returned a data URL without a payload')
}
const binary = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i)
}
if (!startsWithPngSignature(bytes)) {
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
}
return bytes
}
/**
* Rasterizes an SVG string to a PNG byte array using the browser's native
* SVG-to-Image pipeline. The browser parses + draws the SVG via an
* Image/Blob URL pair, which renders identically to what the user sees in
* the inline anatomy canvas.
*
* @param svgString Serialized SVG (must declare `xmlns`)
*/
export async function rasterizeSvg(svgString: string): Promise<Uint8Array> {
const { widthPx, heightPx } = readViewBox(svgString)
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
return canvasToPngBytes(canvas)
}