1

I have an image of a font I would like to draw on an HTML5 Canvas. At first I though about separating each letter into a different image but decided having a sprite sheet would be much cleaner. A problem with that though, is that not all the letters are the same size. Some are a few pixels wider than other characters.

While looking on Google, I came across one way that some people handled the problem. They added a line under each character to represent that characters length and then draw the bottom most line of the font image into an off screen canvas and analyze it pixel by pixel.

Font Example

I tried to implement my own version of that idea, but was unable to get that far. Before I invest more time on that idea, I would like to know if it's a good solution or if there is any better ways of achieving the same thing.

So far I have a few small snippets i'm trying to put together, like this code:

    getImagePixels: function( image, x, y, width, height ) 
    {
        var canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        var ctx = canvas.getContext('2d');


        ctx.drawImage( image, 0, 0, image.width, image.height );

        return ctx.getImageData( x, y, width, height );
    }

and this

    loadFontImage: function( image ) 
    {
        // Draw the bottommost line of this font image into an offscreen canvas
        // and analyze it pixel by pixel.
        // A run of non-transparent pixels represents a character and its width

        this.height = image.height-1;
        this.widthMap = [];
        this.indices = [];

        var px = getImagePixels( image, 0, image.height-1, image.width, 1 );

        var currentChar = 0;
        var currentWidth = 0;

        for( var x = 0; x < image.width; x++ ) 
        {
            var index = x * 4 + 3; // alpha component of this pixel
            if( px.data[index] > 127 ) 
            {
                currentWidth++;
            }
            else if( px.data[index] < 128 && currentWidth ) 
            {
                this.widthMap.push( currentWidth );
                this.indices.push( x-currentWidth );
                currentChar++;
                currentWidth = 0;
            }
        }
    }

1 Answer 1

1

As I can't comment I will just write this as an answer:

You could also simply create or generate a javascript object with all the widths included:

var fontWidths = {
     a: 8,
     b: 8
     ....
};

That way the overhead doesn't happen every time you're going to write something to the canvas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.