@polygonjs/polygonjs
Version:
node-based WebGL 3D engine https://polygonjs.com
64 lines (63 loc) • 2.16 kB
JavaScript
;
import FontFaceObserver from "fontfaceobserver";
function colorStyleWithAlpha(color, alpha) {
const rgb = color.getStyle();
const elements = rgb.split("(")[1].split(")")[0].split(",");
return `rgba(${elements[0]},${elements[1]},${elements[2]},${alpha})`;
}
function writeTextToCanvas(options) {
const { texture, text, fontSize, resolution, bgColor, bgAlpha, textColor, textAlpha, fontFamily } = options;
const canvas = document.createElement("canvas");
canvas.width = resolution.x;
canvas.height = resolution.y;
const ctx = canvas.getContext("2d");
ctx.fillStyle = colorStyleWithAlpha(bgColor, bgAlpha);
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = fontFamily;
ctx.fillStyle = colorStyleWithAlpha(textColor, textAlpha);
let usedFontSize = fontSize;
const metrix = () => ctx.measureText(text);
const usedFont = () => `${usedFontSize}px ${fontFamily}`;
const textWidth = (m2) => m2.width;
const textHeight = (m2) => m2.actualBoundingBoxAscent + m2.actualBoundingBoxDescent;
const isFontTooLarge = (m2) => {
return textWidth(m2) > canvas.width || textHeight(m2) > canvas.height;
};
ctx.font = usedFont();
let m = metrix();
while (isFontTooLarge(m)) {
usedFontSize--;
ctx.font = usedFont();
m = metrix();
}
const positionX = (canvas.width - textWidth(m)) / 2;
const positionY = (canvas.height + textHeight(m) / 2) / 2;
ctx.fillText(text, positionX, positionY);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
texture.source.data = imageData;
texture.needsUpdate = true;
}
export async function loadAndUseFont(options) {
var _a;
const { fontFamily, fontUrl } = options;
const font = new FontFaceObserver(fontFamily);
try {
const style = document.createElement("style");
document.head.appendChild(style);
(_a = style.sheet) == null ? void 0 : _a.insertRule(
`
@font-face {
font-family: '${fontFamily}';
src: url('${fontUrl}');
}
`,
0
);
await font.load();
writeTextToCanvas({
...options
});
} catch (err) {
console.log(`Font is not available: ${err}`);
}
}