I am trying to figure out why the classic way of image preloading before drawing in canvas is firing a "Type error" on chrome.
Let's see the situation:
I try to preload images in 3 different ways:
Or if you prefer some code:
var canvas1 = document.getElementById('canvas-1'),
context1 = canvas1.getContext('2d'),
image1 = new Image(),
canvas2 = document.getElementById('canvas-2'),
context2 = canvas2.getContext('2d'),
image2 = document.createElement('img'),
$canvas3 = $('#canvas-3'),
context3 = $canvas3.get(0).getContext('2d'),
$image3 = $('<img>'),
loadImage = function (image, context, debugIndice) {
debugIndice = debugIndice || -1;
image.onload = function () {
try {
context.drawImage(this, 0, 0, 100, 100);
}
catch (e) {
console.log('error for debugIndice', debugIndice, e, this);
}
}
image.src = "http://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
};
loadImage(image1, context1, 1);
loadImage(image2, context2, 2);
loadImage($image3.get(0), context3, 3);
Please watch the Fiddle here.
I only have a Type error for the first loadImage call.
I am using Google Chrome 27.0.1453.94 on Windows at my company, and Google Chrome 27.0.1453.93 on Mac OS X, both x64 platforms.
This code works fine in Firefox, and even IE9 (I'm not kidding, I swear it)
Does someone knows about this Image() class problem in Chrome ?
EDIT: Here is a screen of the bug:
You can watch it on real size here.
This is not a big problem, anyway I will use the jQuery way, but I am really curious to see what is the cause, and why did I lose some time trying to fix it!
I took a look at this bug.
I am still asking as I am not sure that it is the same ?!
That's not exactly a solution as this is a Chrome bug. But here is the related Chrome bug on their tracker. It is a known issue and should be fix in the - hopefully - near future: https://code.google.com/p/chromium/issues/detail?id=238071
In the meantime, use document.createElement("img")
instead of new Image()
.
It pains me that this worked and I don't have a better answer, but after turning on and off all extensions, trying beta and dev channels, what finally worked was rebooting my computer. Now drawImage works just fine. :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With