0

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;
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Jesper Kristiansen
  • 1,759
  • 3
  • 17
  • 29
  • "Unclear" close votes should usually include a comment saying what isn't clear, so the OP can clarify it. – T.J. Crowder Jun 18 '16 at 14:46
  • 1
    added 'this is typescript'. I did not add the typescript tag as this is not related to TypeScript but rather to html. Sorry about the confusion – Jesper Kristiansen Jun 18 '16 at 15:03
  • sure, it can be marked as duplicate. I did not find the other post in my search as I was looking for fixed with. I'm basically doing the exact same thing, and I jus wasn't sure if there is any better approach to this. But it seems like there is not. – Jesper Kristiansen Jun 20 '16 at 20:44

0 Answers0