1
我想要在HTML5畫布上繪製字體的圖像。起初,我雖然想將每個字母分隔成不同的圖像,但決定讓精靈表更加清潔。但是,這個問題並不是所有的字母都是相同的大小。有些比其他字符寬幾個像素。從HTML5上的圖像中繪製字體Canvas
從Google的角度來看,我遇到了一些解決問題的方法。他們在每個字符下添加一行代表該字符的長度,然後將字體圖像的最底部的一行繪製到屏幕畫布外,並逐個像素地進行分析。
我試圖實現自己的這一想法的版本,但未能走到這一步。在我投入更多時間討論這個想法之前,我想知道這是否是一個好的解決方案,或者是否有更好的方法來實現相同的目標。
到目前爲止,我有幾個小片段我試圖放在一起,這樣的代碼:
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;
}
}
}