Skip to content

Instantly share code, notes, and snippets.

@rayrayzayzay
Created May 12, 2023 21:57
Show Gist options
  • Save rayrayzayzay/436d10c8807143c3cc821e619fb91dce to your computer and use it in GitHub Desktop.
Save rayrayzayzay/436d10c8807143c3cc821e619fb91dce to your computer and use it in GitHub Desktop.
const MIN_FONT_SIZE = 24;
function drawTextElement(ctx, text, fontSize) {
const scale = fontSize / MIN_FONT_SIZE;
if (scale <= 1) {
ctx.scale(scale, scale)
ctx.drawImage(getTexture(text), 0, 0);
} else {
drawText(ctx, text, fontSize)
}
}
function drawText(ctx, text, fontSize) {
ctx.fillText(text, 0, 0);
}
function getTexture(text) {
const fromCache = textureCache.get(text)
if (fromCache) return fromCache;
const newCanvasContext = makeNewCanvasContext();
drawText(newCanvasContext, text, MIN_FONT_SIZE);
textureCache.set(text, newCanvasContext.canvas);
return newCanvasContext.canvas;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment