我有一个字体图像,我想在 HTML5 Canvas 上绘制。起初,我考虑将每个字母分成不同的图像,但认为使用 Sprite 表会更干净。但问题是并非所有字母的大小都相同。有些比其他字符宽几个像素。
在 Google 上查找时,我发现了一些人处理问题的一种方法。他们在每个字符下方添加一条线来表示该字符长度,然后将字体图像的最底线绘制到屏幕外 Canvas 中,并逐像素对其进行分析。
我尝试实现我自己的想法,但没能走到这一步。在我投入更多时间研究这个想法之前,我想知道这是否是一个好的解决方案,或者是否有更好的方法来实现同样的目标。
到目前为止,我正在尝试将一些小片段放在一起,例如以下代码:
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;
}
}
}
最佳答案
因为我无法发表评论,所以我只会写这个作为答案:
您还可以简单地创建或生成一个包含所有宽度的 JavaScript 对象:
var fontWidths = {
a: 8,
b: 8
....
};
这样,每次您要向 Canvas 写入内容时就不会产生开销。
关于javascript - 在 HTML5 Canvas 上从图像中绘制字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25525530/