Javascript: Get text width
Published at 2023-10-19  1 min read

trick to get text widht based on dynamic text and font family, use canvas.

function getTextWidth(text, font) {
    const canvas =
        getTextWidth.canvas ||
        (getTextWidth.canvas = document.createElement("canvas"));
    const context = canvas.getContext("2d");
    context.font = font;
    const metrics = context.measureText(text);
    return metrics.width;
}