@altano/satori-fit-text
Version:
Fit text to a bounding box in Node or the browser
42 lines (40 loc) • 1.4 kB
JavaScript
import log_default from "../log.js";
import { TextMeasurer } from "./TextMeasurer.js";
import { SVG, registerWindow } from "@svgdotjs/svg.js";
import { createSVGWindow } from "svgdom";
//#region src/TextMeasurer/HeadlessTextMeasurer.ts
var HeadlessTextMeasurer = class extends TextMeasurer {
#canvas;
constructor(text, font, maxWidth, maxHeight, lineHeight) {
super(text, font, maxWidth, maxHeight, lineHeight);
const window = createSVGWindow();
const document = window.document;
registerWindow(window, document);
this.#canvas = SVG(document.documentElement);
}
async getDimensions(fontSize) {
await this.#setFontSize(fontSize);
const dimensions = this.#canvas.bbox();
const width = dimensions.width + Math.min(dimensions.x, 0);
const height = dimensions.height + Math.min(dimensions.y, 0);
log_default({
fontSize,
width: `${width}px`,
height: `${height}px`,
widthFits: `${width}px ${width <= this.maxWidth ? "DOES" : "does NOT"} fit in ${this.maxWidth}`,
heightFits: `${height}px ${height <= this.maxHeight ? "DOES" : "does NOT"} fit in ${this.maxHeight}`
});
return {
width,
height
};
}
async #setFontSize(fontSize) {
const svgXML = await this.createSvgXmlString(fontSize);
this.#canvas.clear();
this.#canvas.svg(svgXML);
}
};
//#endregion
export { HeadlessTextMeasurer as default };
//# sourceMappingURL=HeadlessTextMeasurer.js.map