I’ve got a Heisenbug in my code. It only appears every now and then and can’t be triggered deliberately.
FireBug throws an exception like “An invalid or illegal string was specified” at me and refers to a different line every time.
I’m using FireFox 10.0. The website is located at http://www.roboter-club-hamburg.de. I’ve already tried with FireQuery but that interferes with my code so it’s no option.
I’ve tracked it down to a line that looks like this:
context.fillText("[[*longtitle]]", x + 4, y + h + 15, w);
I’m using MODX CMS to build that website (that’s where [[*longtitle]] and [[*id]] and stuff come from; they are template placeholders).
Here’s the full function that this line is in:
($("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;
}));
Alright, I’ve found the cause of this bug. It’s been caused by the fact that the image (img) sometimes was not completely loaded at the time the script asked for its width and height. Hence both were NaN and the script crashed (fillText apparently doesn’t work with a width of NaN).
Now, all I’ve done to solve this problem is to move the drawing steps into the onload callback of img. That works. This Heisenbug is no more.
Thanks a lot!