Is there any easy way to reliably obtain the character width of a fixed font of a DOM element?.
I have come up with this somewhat hacky approach shown here which seems to work, but there must be a better way of doing this.
Here I get the text height from the text area element I render (trying to create a simple editor). I append it to the editor element (editorArea), this element contains the font used by my editor. I then calculate the width and removed the element.
Edit: this is TypeScript.
let lineHeight: number = this._context.textArea.lineHeight;
let textHeight: number = this._context.textArea._textHeight;
let textMeasure = $('<span class="testArea" >');
textMeasure.css("line-height", `${lineHeight}px`);
textMeasure.css("font-size", `${textHeight}px`);
textMeasure.css("padding", `0`);
textMeasure.css("margin", `0`);
textMeasure.text('.123456789.123456789.123456789.123456789.123456789');
this._context.textArea.editorArea.append(textMeasure);
let w = textMeasure.width();
let p = w / textMeasure.text().length;
console.log('width of test area = ' + w + ', per character = ' + p);
this._context.textArea._textWidth = p;
textMeasure.remove();
textMeasure = null;