Javascript 从HTML5画布上的图像绘制字体
我有一个我想在HTML5画布上绘制的字体图像。起初,我想把每个字母分成不同的图像,但决定用一张精灵纸会更干净。但问题是,并非所有字母的大小都相同。有些字符比其他字符宽几个像素 在浏览谷歌时,我发现了一种方法,一些人处理了这个问题。他们在每个字符下添加一条线来表示该字符的长度,然后将字体图像的最下面一行绘制到屏幕外的画布上,并逐像素分析 我试图实现我自己的想法,但没能做到这一点。在我花更多时间研究这个想法之前,我想知道这是一个好的解决方案,还是有更好的方法来实现同样的目标 到目前为止,我有一些小片段正在尝试整理,如以下代码:Javascript 从HTML5画布上的图像绘制字体,javascript,html,canvas,fonts,sprite-sheet,Javascript,Html,Canvas,Fonts,Sprite Sheet,我有一个我想在HTML5画布上绘制的字体图像。起初,我想把每个字母分成不同的图像,但决定用一张精灵纸会更干净。但问题是,并非所有字母的大小都相同。有些字符比其他字符宽几个像素 在浏览谷歌时,我发现了一种方法,一些人处理了这个问题。他们在每个字符下添加一条线来表示该字符的长度,然后将字体图像的最下面一行绘制到屏幕外的画布上,并逐像素分析 我试图实现我自己的想法,但没能做到这一点。在我花更多时间研究这个想法之前,我想知道这是一个好的解决方案,还是有更好的方法来实现同样的目标 到目前为止,我有一些小
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;
}
}
}
loadFontImage:函数(图像)
{
//将此字体图像的最底行绘制到屏幕外画布中
//并逐像素分析。
//一系列不透明像素表示字符及其宽度
this.height=image.height-1;
this.widthMap=[];
该指数为[];
var px=getImagePixels(image,0,image.height-1,image.width,1);
var currentChar=0;
var currentWidth=0;
对于(var x=0;x127)
{
currentWidth++;
}
else if(px.data[索引]<128&¤tWidth)
{
此.widthMap.push(当前宽度);
此.index.push(x-currentWidth);
currentChar++;
currentWidth=0;
}
}
}
由于我无法发表评论,我将写下以下内容作为回答:
您也可以简单地创建或生成包含所有宽度的javascript对象:
var fontWidths = {
a: 8,
b: 8
....
};
这样就不会每次在画布上写东西时都会产生开销