filltext()画布文本位置浏览器之间的差异

Tyl*_*ler 8 javascript firefox internet-explorer canvas

可以在问题底部的截图中看到,也可以 直接进入游戏.文本的放置取决于浏览器(firefox 15.0.1的呈现方式与IE 9.9和Chrome 21不同).调用绘图功能:

context.fillText(this.wlines[i], this.xcoord, this.ycoord + y + (t) * this.sizey);
Run Code Online (Sandbox Code Playgroud)

对象的构造函数:

function textItem(text, xcoord, ycoord, sizex, sizey,style, context) {
this.wlines = [];
this.text = text;
this.xcoord = xcoord;
this.ycoord = ycoord;
this.sizex = sizex;
this.sizey = sizey;
this.style = style;

if (text == null) {
    text = "";
}
var lines = text.split("~");
// this is first line text
context.save();
if (this.style < 3) {
    context.shadowOffsetY = 2;
    context.font = 'bold 18px "palatino linotype"';
} else if (this.style == 4) {
    this.font = '16px "palatino linotype"';
    this.shadowOffsetX = 2;
    this.shadowOffsetY = 1;
    this.shadowColor = "rgba(255,255,255,1)";
}
if (this.style == 5) {
    this.wlines.push(text);
} else {
    for (j = 0; j < lines.length; j += 1) {
        var words = lines[j].split(" ");
        var lastLine = "";
        var l = sizex;
        var measure = 0;
        for (i = 0; i < words.length; i += 1) {
            var w = words[i];
            measure = context.measureText(lastLine + w).width;
            if (measure < l) {
                lastLine += (w + " ");
            } else {
                //this is body text
                if (this.style == 6) {
                    lastLine += "...";
                }
                this.wlines.push(lastLine);
                lastLine = (w + " ");
                if (this.style < 3) {
                    context.font = 'bold 14px "palatino linotype"';
                }
            }
            if (i == words.length - 1) {
                this.wlines.push(lastLine);
                break;
            }
        }
    }
}
context.restore();
}
Run Code Online (Sandbox Code Playgroud)

text,xcoorc,ycoord,xsize,ysize是从xml文件中解析出来的.此示例中的compond名称:

<sizex>196</sizex>
<sizey>20</sizey>
<xcoord>383</xcoord>
<ycoord>14</ycoord>
Run Code Online (Sandbox Code Playgroud)

style是基于所需文本效果的定义值,context是要绘制的画布的2d上下文(用于分层效果).

如图所示,浏览器之间的所有值完全相同.我在浏览器之间做的唯一检查是

<meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"/>
Run Code Online (Sandbox Code Playgroud)

在html页面的标题中.

我真的不知道线高差异来自哪里,对此事的任何帮助都将不胜感激.

行高差异会根据文本而变化,但不会以我已经想到的方式变化.如果有任何我遗漏的信息,请不要犹豫.ff: ff屏幕http://www.sunshinecompound.com/images/firefoxscreen.png Chrome: 镀铬屏幕http://www.sunshinecompound.com/images/googlescreen.png

更新我的程序的解决方案至少是构建使用偏移量.此外,通过创建文本对象然后将文本对象保存为图像,我获得了巨大的性能提升.在FF是最慢的浏览器,我看到整体程序运行时间减少了5倍.尽管这是不必重新创建文本对象在程序中动态地改变每个时间文本(我改变每秒和鼠标悬停特效动态计数器每200ms,但与性能我目前得到我大概可以提高该为100ms).

Sim*_*ris 3

是的。

它在浏览器之间的放置、缩放、字距、别名、甚至测量方式都不同(如measureText)。

如果您的游戏需要像素一致性,那么您将不得不使用图像而不是文本。对不起。:(

保持一致的唯一方法measureText是预先计算。

保持一致的唯一方法fillText是使用图像而不是文本。无论如何,它必须更快

如果文本极其动态,那么这两种方法都是站不住脚的,但如果您只在应用程序中编写少于 100 条不同的文本,那么图像可能是您最好的选择。

否则,您可以使用从图像生成的像素字体(对每个字母或常用单词使用drawImage)并希望获得良好的性能,缓存较长的常用字符串。