【问题标题】:Canvas fillText not rendering画布填充文本未呈现
【发布时间】:2017-01-04 09:55:03
【问题描述】:

请看我关于这个问题的 jsfiddle

https://jsfiddle.net/gL4m2z6v/

这是一个画布中的分数计算器,应该显示两个分数之间的最大公因数。您将需要在小提琴中展开视口并重新运行才能正确查看。

相关代码摘录 - 查看完整的小提琴

labelGCF: function(a, b){
    var b = a % b;
    if (b != 0) {
        console.log(a, window.innerWidth*0.8, winH50, textObj.fontSize);
        ctx.fillText(a, window.innerWidth*0.8, winH50, textObj.fontSize);
    } else {
        tableObj.labelGCF(b, a % b);
    }
}

// Exec
(function loop(){
    window.requestAnimationFrame(loop);
    // Draw Canvas Background
    c.width = canWidth;
    c.height = canHeight;
    ctx.fillStyle = "#fff";
    ctx.fillRect(0,0,canWidth,canHeight);
    // Draw Arrows
    arrowObj.draw(arrowObj[0]);
    arrowObj.draw(arrowObj[1]);
    arrowObj.draw(arrowObj[2]);
    arrowObj.draw(arrowObj[3]);
    coordsObj.arrows = 
    [arrowObj.getCoords(arrowObj[0]), arrowObj.getCoords(arrowObj[1]), arrowObj.getCoords(arrowObj[2]), arrowObj.getCoords(arrowObj[3])];
    // console.log("coordsObj.arrows: "+coordsObj.arrows);
    // Draw Table
    tableObj.draw();
    tableObj.labelXAxis();
    tableObj.labelYAxis();
    tableObj.labelTable();
    tableObj.drawGrid();
    tableObj.labelGCF(tableObj.xCount, tableObj.yCount);

})();

此代码似乎可以执行,并且变量已正确排除。我不知道为什么 fillText 不起作用。

【问题讨论】:

  • ctx.fillText之前console.log的输出是什么?
  • 看看这个documentation 并纠正你的论点。 "0" 将绘制在位置 (1536, 489.5)
  • 是的,但对我来说没有出现。您是否尝试过小提琴或 dl 代码并全屏使用。即使坐标在视口内,它也不会在屏幕上绘制 0。

标签: javascript canvas


【解决方案1】:

首先,确保您的fillText 坐标在画布内。一个 1536 的 x 可能在画布右侧。同上,y 为 489.5。

第二fillText 的最后一个参数是画布用于显示文本的最大宽度。任何不适合该宽度的文本都将被截断。您指定的 textObj.fontSize (==48) 似乎与最大宽度无关。所以你可能想把这个论点排除在外。

并且 ...如果需要,您可以使用 textAligntextBaseline 将文本水平和垂直居中于指定的 x,y 上:

// center text horizontally at [x,y]
ctx.textAlign='center';

// center text vertically at [x,y]
ctx.textBaseline='middle';

// draw your text (it will be centered at the specified x,y)
ctx.fillText('Centered Text', x,y );

【讨论】:

  • 嗨,markE,我运行 1920x1080,所以文本应该出现在视口内。我很好奇你的回复中的最大宽度,即第二个......我认为这是像 48px 字体大小的像素,即 48px 宽。我对渲染的其他文本使用相同的代码,所以我仍然很难过。
  • @MichaelPaccione。好吧,这绝对是限制显示宽度为 48 像素的参数。如果你总是有 1 个字符,那么一切都很好,但更宽的文本会被截断。
  • 是的,原来填充文本设置为白色,而我认为它是黑色的,我看不到白色背景下的文本。大声笑:/
【解决方案2】:

我不敢相信。我最终玩了坐标,并意识到 fillText 是白色的。我在该死的近 90% 的代码中使用黑色。几个小时过去了。啊,编程的乐趣。谢谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2012-05-02
    • 2016-07-25
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多