89 lines
2.7 KiB
TypeScript
89 lines
2.7 KiB
TypeScript
import { Resvg } from '@resvg/resvg-js'
|
|
import type { Rasterizer } from '../../src'
|
|
|
|
/**
|
|
* A real Node rasterizer for T10. resvg 0.40 (resvg-js 2.6.2) panics
|
|
* (`geom.rs:27`, `Option::unwrap() on None`) when gradient-filled elements
|
|
* are culled by a cropped root `viewBox` such as the head view's
|
|
* `60 100 500 380` on the equine drawing, aborting the process. The
|
|
* adapter therefore renders the box covering the whole content at the
|
|
* same scale and crops the pixels to the requested view: identical output
|
|
* for a view that already covers its content (main view).
|
|
*/
|
|
|
|
export interface Raster {
|
|
requested: { widthPx: number; heightPx: number }
|
|
png: Uint8Array
|
|
}
|
|
|
|
interface Box {
|
|
x: number
|
|
y: number
|
|
width: number
|
|
height: number
|
|
}
|
|
|
|
const FONT = { loadSystemFonts: false }
|
|
|
|
function rootViewBox(svg: string): Box | null {
|
|
const tag = svg.match(/<svg\b[^>]*>/)?.[0] ?? ''
|
|
const raw = tag.match(/\sviewBox="([^"]+)"/)?.[1]
|
|
if (!raw) return null
|
|
const [x, y, width, height] = raw
|
|
.trim()
|
|
.split(/[\s,]+/)
|
|
.map(Number)
|
|
if (!(width! > 0) || !(height! > 0)) return null
|
|
return { x: x!, y: y!, width: width!, height: height! }
|
|
}
|
|
|
|
function withViewBox(svg: string, box: Box): string {
|
|
const value = `${box.x} ${box.y} ${box.width} ${box.height}`
|
|
return svg.replace(/(<svg\b[^>]*?\sviewBox=")[^"]+(")/, `$1${value}$2`)
|
|
}
|
|
|
|
function union(a: Box, b: Box): Box {
|
|
const x = Math.min(a.x, b.x)
|
|
const y = Math.min(a.y, b.y)
|
|
return {
|
|
x,
|
|
y,
|
|
width: Math.max(a.x + a.width, b.x + b.width) - x,
|
|
height: Math.max(a.y + a.height, b.y + b.height) - y,
|
|
}
|
|
}
|
|
|
|
function contentBox(svg: string): Box | null {
|
|
const bbox = new Resvg(svg, { font: FONT }).getBBox()
|
|
if (!bbox || !(bbox.width > 0) || !(bbox.height > 0)) return null
|
|
return { x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height }
|
|
}
|
|
|
|
export function resvgRasterizer(record: Raster[] = []): Rasterizer {
|
|
return async (svg, size) => {
|
|
const crop = rootViewBox(svg)
|
|
const content = crop ? contentBox(svg) : null
|
|
const full = crop && content ? union(crop, content) : crop
|
|
const scale = crop ? size.widthPx / crop.width : 1
|
|
const left = Math.round(((crop?.x ?? 0) - (full?.x ?? 0)) * scale)
|
|
const top = Math.round(((crop?.y ?? 0) - (full?.y ?? 0)) * scale)
|
|
const resvg = new Resvg(full ? withViewBox(svg, full) : svg, {
|
|
fitTo: {
|
|
mode: 'width',
|
|
value: full ? Math.round(full.width * scale) : size.widthPx,
|
|
},
|
|
background: 'white',
|
|
font: FONT,
|
|
crop: {
|
|
left,
|
|
top,
|
|
right: left + size.widthPx,
|
|
bottom: top + size.heightPx,
|
|
},
|
|
})
|
|
const png = new Uint8Array(resvg.render().asPng())
|
|
record.push({ requested: size, png })
|
|
return png
|
|
}
|
|
}
|