textWidth
Given a text string, returns the predicted pixel width of the string when placed into DOM.
Array input
Section titled “Array input”Pass an array to measure many strings at once and get an array of widths back in the same order, which is how textWrap sizes every word of a sentence in one call.
import {textWidth} from "@d3plus/dom";
textWidth(["alpha", "beta", "gamma"], {
"font-family": "Inter",
"font-size": 16,
});
Basic example
Section titled “Basic example”Predicts the pixel width a string will occupy at a given font without rendering it, using the font’s actual glyph metrics, which is why WWW and iii differ so much. Every label, axis tick, and legend entry is measured this way before it is placed.
import {textWidth} from "@d3plus/dom";
textWidth("Hello", {"font-family": "Inter", "font-size": 16});
textWidth("Hello world", {"font-family": "Inter", "font-size": 16});
textWidth("WWW", {"font-family": "Inter", "font-size": 16});
textWidth("iii", {"font-family": "Inter", "font-size": 16});
Font styles
Section titled “Font styles”The style object takes CSS property names: font-size (a number means pixels), font-weight, and font-family all change the result, and a family list falls through to the first installed font just as CSS would.
import {textWidth} from "@d3plus/dom";
textWidth("Sphinx of black quartz", {"font-family": "Inter", "font-size": 12});
textWidth("Sphinx of black quartz", {"font-family": "Inter", "font-size": 24});
textWidth("Sphinx of black quartz", {
"font-family": "Inter",
"font-size": 16,
"font-weight": 700,
});
textWidth("Sphinx of black quartz", {
"font-family": "Georgia, serif",
"font-size": 16,
});
Parameters
import {textWidth} from "@d3plus/dom";