Last active
February 1, 2025 13:57
-
-
Save jernkuan/e92b1ad4270f567c045c3f3684b4c3f1 to your computer and use it in GitHub Desktop.
Anki autoscaling font size for card type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{#Front}} | |
<script defer> | |
function lerp(start, stop, amt) { | |
return (1 - amt) * start + amt * stop; | |
} | |
// Function to estimate text width using canvas | |
function estimateTextWidth(text, fontSize) { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
ctx.font = `${fontSize}px sans-serif`; // Adjust font family as needed | |
return ctx.measureText(text).width; | |
} | |
// Function to update font size when the field changes | |
function updateFontSize() { | |
const textElements = document.querySelectorAll('.your-field-class'); | |
textElements.forEach(function(element) { | |
const text = element.textContent; | |
const containerWidth = element.parentElement.offsetWidth - 100; | |
// Initial font size guess | |
let fontSize = 50; // Adjust initial guess as needed | |
// Calculate target font size | |
fontSize = fontSize * (containerWidth / estimateTextWidth(text, fontSize)); | |
// Limit font size to a reasonable maximum (optional) | |
const maxFontSize = 300; | |
fontSize = Math.min(fontSize, maxFontSize); | |
element.innerHTML = `<span style="font-size: ${fontSize}px;">${text}</span>`; | |
}); | |
} | |
// Initial call to update font size | |
updateFontSize(); | |
</script> | |
<div class="your-field-class">{{Front}}</div> | |
{{/Front}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment