I need to find the width of a character in an HTML textarea element, in CSS px
.
The best solution would use a JavaScript function that takes a character and returns its width, and must work with special characters like control characters (u0001
, u0096
, uFFFD
etc.) It would be even better if it also worked with Tabs given the index of the character in the textarea.
I already have a function that does this (link here; my project is open-source and on GitHub) using an HTML5 textarea and works on Chromium, but it breaks in Firefox, especially since Firefox renders control characters differently in textareas ("hex boxes") to other elements.
getCharacterWidth(char) {
// Force zero-width characters
if(new RegExp("u00AD|u02de|[u0300-u036F]|[u0483-u0489]|u200b").test(char) ) { return 0 }
// Non-renderable ASCII characters should all be rendered at same size
if(char != "u0096" && new RegExp("[u{0000}-u{001F}]|[u{007F}-u{009F}]", "g").test(char)) {
let fallbackWidth = this.getCharacterWidth("u0096");
return fallbackWidth;
}
// Lazy-load - TODO: Get a cleaner way of doing this
if(char in this.cachedWidths) {
return this.cachedWidths[char];
}
// Try to get width
let width = this.canvasContext.measureText(char).width;
this.canvasContext.fillText(char, 100, 100);
if(width > 20) {
width /= 2; // Fix double-width-in-canvas Firefox bug
} else if(width == 0 && char != "u0096") {
let fallbackWidth = this.getCharacterWidth("u0096");
return fallbackWidth; // In Firefox some control chars don't render, but all control chars are the same width
}
this.cachedWidths[char] = width;
return width;
}
I would very much appreciate suggestions here, or a PR in the project on GitHub forked from the display-special-chars
branch. Thank you for your help.
3
Answers
Look at this code.
I think this will help you.
You can call this function with a character and a textarea element to get the width of the character in pixels: