在决定应该使用什么字体大小之前,我编写了简单的函数来测量文本。
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
svg.appendChild(text);
interface HeightAndWidth {
width: number;
height: number;
}
interface MeasureProps {
label: string;
fontFamily: string;
size: number;
fontWeight?: number;
lineHeight?: number;
letterSpacing?: string;
}
export const measureText = ({
label,
fontFamily,
size,
fontWeight = 400,
lineHeight = 1,
letterSpacing = '0',
}: MeasureProps): HeightAndWidth => {
text.setAttribute('font-size', `${size}px`);
text.setAttribute('line-height', `${lineHeight}px`);
text.setAttribute('font-family', fontFamily);
text.setAttribute('font-weight', `${fontWeight}`);
text.setAttribute('letter-spacing', letterSpacing);
text.textContent = label;
document.body.appendChild(svg);
const { width, height } = text.getBBox();
return …Run Code Online (Sandbox Code Playgroud)