我的代码中有一个 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/