Using "new Image()" in extension creates wrong object


Recommended Posts

I've just run into a strange bug - running this correct code (from an extension) :var img = new Image();

img.src = '...';

...

ctx.drawImage(img,0,0);...will throw a Type Error, whilevar img = document.createElement('img');

img.src = '...';

...

ctx.drawImage(img,0,0);...works.

Turns out this bug also affected Chrome since a more than a year old update:

https://code.google.com/p/chromium/issues/detail?id=238071

Link to comment
Share on other sites

Why are you trying to draw an empty image, anyway? First of all you need an src, then you need to add an onload event for the image element, and only then draw it on canvas, you also don't have width and height in drawImage function, here's an example how it should look like:var canvas=document.createElement('canvas')

var context=canvas.getContext('2d')

var image=new Image

image.addEventListener('load',function(){

    canvas.width=image.width

    canvas.height=image.height

    context.drawImage(image,0,0,image.width,image.height)

})

image.src='http://my.imagecache.maxthon.com/avatar/2/065/2065060/1311276529.png'

Link to comment
Share on other sites

Sorry for the confusion - that was just an example. I was, of course, using an image with correct source.

Here's a better example of this problem. If I use "var original = new Image()" it crashes on the type error. If I use "var original = document.createElement('img')" it works. And the rest of the code is always the same.

But it may be a problem only for scripts ran by extensions...

post-2065060-14315122312343_thumb.jpg

post-2065060-14315122312431_thumb.jpg

Link to comment
Share on other sites

Try running this from the console:var c = document.createElement('canvas').getContext('2d'); c.fillRect(5,5,10,10); var iDCE = document.createElement('img'); var iNew = new Image(); iNew.src = c.canvas.toDataURL(); iDCE.src = c.canvas.toDataURL(); console.log(iDCE,iNew); c.drawImage(iDCE,0,0); console.log('DCE ok'); c.drawImage(iNew,0,0); console.log('New ok');

Link to comment
Share on other sites

Yup, pretty much what you say. Weird.

Also that code I posted above started to work for me since I have updated my 4.4.3.800 version to 4.4.3.2000. It was throwing the type error even in the console, not using the extension. So that seems to be fixed...

But extensions still mess the Image object up.

Link to comment
Share on other sites