108 lines
3.6 KiB
TypeScript
108 lines
3.6 KiB
TypeScript
/**
|
|
* The browser side of the core's raster requests (R4.6; the engine's adapter
|
|
* before): the core has fixed the pixel size, this module only stamps it on
|
|
* the SVG root and lets the browser draw the SVG through an Image / canvas
|
|
* pair, which renders exactly what the practitioner sees in the inline
|
|
* anatomy canvas.
|
|
*/
|
|
|
|
export interface RasterSize {
|
|
widthPx: number
|
|
heightPx: number
|
|
}
|
|
|
|
/** Draws `svg` at `size` as a PNG. */
|
|
export type Rasterizer = (svg: string, size: RasterSize) => Promise<Uint8Array>
|
|
|
|
const SVG_NS = 'http://www.w3.org/2000/svg'
|
|
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
|
|
|
function startsWithPngSignature(bytes: Uint8Array): boolean {
|
|
if (bytes.length < PNG_SIGNATURE.length) return false
|
|
return PNG_SIGNATURE.every((byte, i) => bytes[i] === byte)
|
|
}
|
|
|
|
/** The root carries the namespace and the engine's size; nothing else changes. */
|
|
function sizedSvg(svg: string, widthPx: number, heightPx: number): string {
|
|
const root = new DOMParser().parseFromString(
|
|
svg,
|
|
'image/svg+xml',
|
|
).documentElement
|
|
if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS)
|
|
root.setAttribute('width', String(widthPx))
|
|
root.setAttribute('height', String(heightPx))
|
|
return new XMLSerializer().serializeToString(root)
|
|
}
|
|
|
|
function loadImage(svg: string): Promise<HTMLImageElement> {
|
|
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
|
|
const url = URL.createObjectURL(blob)
|
|
const img = new Image()
|
|
img.decoding = 'sync'
|
|
img.crossOrigin = 'anonymous'
|
|
return new Promise<HTMLImageElement>((resolve, reject) => {
|
|
img.onload = () => resolve(img)
|
|
img.onerror = () =>
|
|
reject(new Error('Browser failed to render the SVG into an Image'))
|
|
img.src = url
|
|
}).finally(() => URL.revokeObjectURL(url))
|
|
}
|
|
|
|
function drawOnWhiteCanvas(
|
|
img: HTMLImageElement,
|
|
widthPx: number,
|
|
heightPx: number,
|
|
): HTMLCanvasElement {
|
|
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
|
|
}
|
|
|
|
function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob | null> {
|
|
return new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
|
|
}
|
|
|
|
/** Fallback when toBlob yields nothing: decode the data URL by hand. */
|
|
function pngFromDataUrl(canvas: HTMLCanvasElement): Uint8Array {
|
|
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
|
|
}
|
|
|
|
async function canvasToPng(canvas: HTMLCanvasElement): Promise<Uint8Array> {
|
|
const blob = await canvasBlob(canvas)
|
|
if (blob) {
|
|
const bytes = new Uint8Array(await blob.arrayBuffer())
|
|
if (startsWithPngSignature(bytes)) return bytes
|
|
}
|
|
return pngFromDataUrl(canvas)
|
|
}
|
|
|
|
export const browserRasterizer: Rasterizer = async (
|
|
svg,
|
|
{ widthPx, heightPx },
|
|
) => {
|
|
const img = await loadImage(sizedSvg(svg, widthPx, heightPx))
|
|
return canvasToPng(drawOnWhiteCanvas(img, widthPx, heightPx))
|
|
}
|