get-text-metrics v1.4.0
get-text-metrics
🖊️ Measure text using the Canvas API.
Introduction
Measuring text performantly in the browser isn't as straightforward as one would think—the recommended way is to leverage the Canvas API (and its measureText method) instead of relying on the DOM directly. getTextMetrics embraces this way into a single function and attempts to smooth out the differences between the DOM and the Canvas API.
When supported, getTextMetrics will leverage an OffscreenCanvas from a Worker to measure in a background thread.
Installation
Skypack
<script type="module">
import { getTextMetrics } from "https://cdn.skypack.dev/get-text-metrics"
</script>Yarn
yarn add get-text-metricsnpm
npm install get-text-metricsUsage
Import getTextMetrics.
import { getTextMetrics } from "get-text-metrics"Invoke it asynchronously with a string and access its TextMetrics in return.
const metrics = await getTextMetrics(
"With impressions chosen from another time."
)
// metrics: TextMetricsGiven an array of strings instead, getTextMetrics will return an array of TextMetrics.
const metrics = await getTextMetrics([
"With impressions chosen from another time.",
"Underneath a sky that's ever falling down."
])
// metrics: [TextMetrics, TextMetrics]Font
A secondary argument can be set to specify a font appearance—from properties, a font string, or a CSSStyleDeclaration.
Properties
Specify individual font properties as an object with fontFamily, fontSize, fontStretch, fontStyle, fontVariant, fontWeight, and lineHeight.
const metrics = await getTextMetrics("", {
fontFamily: "cursive",
fontSize: 16,
fontStyle: "italic",
fontWeight: 500,
fontVariant: "small-caps",
lineHeight: 2
})string
Specify all font properties as a font shorthand string.
const metrics = await getTextMetrics("", "italic small-caps 500 16px/2 cursive")CSSStyleDeclaration
Specify a CSSStyleDeclaration from which to extract font properties.
const paragraph = document.querySelector("p")
const metrics = await getTextMetrics("", window.getComputedStyle(paragraph))