const measureWidth = function (text, font) {// Create new `canvas` elementconst canvas = document.createElement('canvas');// Get the contextconst context = canvas.getContext('2d');// Set the fontcontext.font = font;// Measure the textconst metrics = context.measureText(text);// Return the width in pixelsreturn metrics.width;};
const measureWidth = function (text, font) {// Create an elementconst ele = document.createElement('div');// Set stylesele.style.position = 'absolute';ele.style.visibility = 'hidden';ele.style.whiteSpace = 'nowrap';ele.style.left = '-9999px';// Set font and textele.style.font = font;ele.innerText = text;// Append to the bodydocument.body.appendChild(ele);// Get the widthconst width = window.getComputedStyle(ele).width;// Remove the elementdocument.body.removeChild(ele);return width;};