javascript - Canvas context.fillText 抛出 “An invalid or illegal string was specified”

标签 javascript jquery html html5-canvas

我的代码中有一个 Heisenbug。它只是偶尔出现,无法刻意触发。

FireBug 向我抛出“指定了无效或非法字符串”之类的异常,并且每次都引用不同的行。

我使用的是 FireFox 10.0。网站位于http://www.roboter-club-hamburg.de 。我已经尝试过使用 FireQuery,但这会干扰我的代码,因此别无选择。


我已经追踪到如下一行:

context.fillText("[[*longtitle]]", x + 4, y + h + 15, w);

我正在使用 MODX CMS 来构建该网站(这就是 [[*longtitle]][[*id]] 等内容的来源;它们是模板占位符)。

这是该行所在的完整函数:

($("imagecvs-[[*id]]").ready(function() {
    var canvas = $("#imagecvs-[[*id]]").get(0);
    if (canvas.getContext) {
    var context = canvas.getContext('2d');
    var img = new Image();

    img.src = "[[*Photo]]";

    var scale = 0.6;
    var ratio = img.width / img.height;

    var w = Math.min(img.width * scale, 120);
    var h = w / ratio;
    var x = 0;
    var y = (canvas.height / 2.0) - (h / 2.0);

    var deg = -8;
    var rad = (deg * Math.PI / 180);
    // y += (h / 2) * -Math.sin( rad );
    context.rotate(rad);

    context.fillStyle = "#FFF";
    context.fillRect(x - 5, y - 5, w + 10, h + 30);
    context.drawImage(img, x, y, w, h);

    context.font = "Italic Bold 10px Serif";
    context.textAlign = "left";
    context.textBaseline = "ideographic";
    context.fillStyle = "#000";
    context.fillText("This is a test", x + 4, y + h + 15, w); // Exception thrown here; even with 'This is a test'
    }
    return true;
  }));

最佳答案

好的,我已经找到这个bug的原因了。这是由于图像(img)有时在脚本请求其宽度和高度时未完全加载而引起的。因此,两者都是 NaN 并且脚本崩溃了(fillText 显然不适用于 NaN 的宽度)。

现在,我为解决这个问题所做的就是将绘制步骤移至img的onload回调中。这样可行。这个 Heisenbug 已经不复存在了。

非常感谢!

关于javascript - Canvas context.fillText 抛出 “An invalid or illegal string was specified”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9209327/

相关文章:

javascript - 在页面上的 div 中显示 HREF 链接

javascript - 使用js更新表单字段但未在提交的数据中显示

javascript - 用于将 XML 转换为 XHTML 的 Firefox 附加组件

html - 为什么将移动设备从横向旋转到纵向后,网页会放大?

html - Chrome : user agent stylesheet turn off for transparent background

javascript - 如何访问 javascript/typescript 中的重复项计数

javascript - 使链接在新页面上的 iframe 中加载内容

jquery - 按值(value)计算百分比或按百分比计算值(value)

javascript - 内部 html 被 javascript 更改后自动调整 div 高度

javascript - JQuery - 在 window.location 之后使用 $(document).ready()