从 HTML5 Canvas 上的图像绘制字体

Posted

技术标签:

【中文标题】从 HTML5 Canvas 上的图像绘制字体【英文标题】:Draw font from Image on HTML5 Canvas 【发布时间】:2014-10-20 22:36:51 【问题描述】:

我有一张我想在 html5 画布上绘制的字体图像。起初我想把每个字母分成不同的图像,但决定有一个精灵表会更干净。但是,一个问题是并非所有字母的大小都相同。有些比其他字符宽几个像素。

在查看 Google 时,我发现了一些人处理问题的一种方式。他们在每个字符下添加了一条线来表示该字符的长度,然后将字体图像的最底部线绘制到屏幕外的画布中,并逐个像素地对其进行分析。

我尝试实现我自己版本的这个想法,但无法做到这一点。在我为这个想法投入更多时间之前,我想知道它是否是一个好的解决方案,或者是否有更好的方法来实现同样的目标。

到目前为止,我正在尝试将一些小的 sn-ps 放在一起,例如以下代码:

    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 );
    

还有这个

    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】:

由于我无法发表评论,所以我会写这个作为答案:

您也可以简单地创建或生成一个包含所有宽度的 javascript 对象:

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

这样,每次你要在画布上写东西时,开销就不会发生。

【讨论】:

以上是关于从 HTML5 Canvas 上的图像绘制字体的主要内容,如果未能解决你的问题,请参考以下文章

在 Angular.js 上的 HTML5 Canvas 中的背景图像上绘制一个矩形

在 HTML5 Canvas 中绘制图像,同时保留图像

HTML5 Canvas 填充文本和字体

HTML5 Canvas - 如何在画布中的图像上绘制矩形

HTML5 Canvas ~ 使用绘制元素平滑快速缩放,而不是图像 ~ 如何?

HTML5 Canvas 学习笔记(canvas绘制线条矩形多边形圆形圆环组合图形文字自定义图像)