skip to Main Content

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


  1. Look at this code.

    // create a new canvas element
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    // set the font size and type
    ctx.font = '16px Arial';
    
    // get the width of the character 'A'
    const charWidth = ctx.measureText('A').width;
    console.log(`The width of the character 'A' is ${charWidth}px`);
    

    I think this will help you.

    Login or Signup to reply.
  2. In JavaScript, you can find the width of a character in a textarea by creating a temporary element, setting its font to match the font of the textarea, and then measuring the width of the character in the temporary element using the offsetWidth property. Here’s an example function that takes a character and a textarea element, and returns the width of the character in pixels

    function getCharacterWidth(char, textarea) {
    // Create a temporary element to measure the width of the character
    const temp = document.createElement('span');
    temp.textContent = char;
    
    // Copy the textarea's font to the temporary element
    temp.style.font = getComputedStyle(textarea).font;
    
    // Add the temporary element to the document so we can measure its width
    document.body.appendChild(temp);
    
    // Get the width of the character in pixels
    const width = temp.offsetWidth;
    
    // Remove the temporary element from the document
    document.body.removeChild(temp);
    
    return width;
    }
    

    You can call this function with a character and a textarea element to get the width of the character in pixels:

    const charWidth = getCharacterWidth('a', 
    document.querySelector('textarea'));
    console.log(`The width of the character 'a' in the textarea is 
    ${charWidth}px`);
    
    • Note that this function only works for monospaced fonts. If the textarea uses a proportional font, the width of each character will vary depending on the specific character and the surrounding text.
    Login or Signup to reply.
  3. 
    function getCharWidthInTextarea(char, textarea) {
        // Create a temporary span element with the same font properties as the textarea
        var span = document.createElement('span');
        span.style.fontSize = window.getComputedStyle(textarea).fontSize;
        span.style.fontFamily = window.getComputedStyle(textarea).fontFamily;
        span.style.fontWeight = window.getComputedStyle(textarea).fontWeight;
        span.style.visibility = 'hidden';
        span.style.position = 'absolute';
        span.textContent = char;
    
        // Append the span element to the document body
        document.body.appendChild(span);
    
        // Get the width of the character using the offsetWidth property of the span 
        var width = span.offsetWidth;
    
        // Remove the span element from the document body
        document.body.removeChild(span);
    
        // Return the width of the character
        return width;
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search