Wednesday, 15 February 2012

javascript - image onload not working , error Uncaught TypeError: Type error -



javascript - image onload not working , error Uncaught TypeError: Type error -

i want draw images using image = new image();

i define new varible 3 different images.

when run code error "uncaught typeerror: type error "

how prepare correctly code draw images include in varible images.

demo jsffidle

many thanks.

var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); canvas.width = 1000; canvas.height = 500; var background = { p1: { url : "http://flora4me.com/im/b/1149.jpg",x: 5, y: 5, w: 1280, h: 480 , dx:0 ,dy:0 ,dw:500 ,dh:500 }, p2: { url : "http://flora4me.com/im/b/1119.jpg",x: 5, y: 495, w: 1280, h: 480 , dx:100 ,dy:100 ,dw:500 ,dh:500}, p3: { url : "http://vladfilippov.com/blog/2012-12-07/intro.jpg",x: 5, y: 985, w: 1280, h: 480 , dx:200 ,dy:200 ,dw:500 ,dh:500 } }; var image; (var n in background) { image = new image(); image.src = background[n].url; image.onload = function() { ctx.drawimage(image, background[n].x,background[n].y, background[n].w, background[n].h, background[n].dx, background[n].dy, background[n].dw, background[n].dh ); }; }

now you're drawing p3 3 times rather iterate on background. though won't explain "type error". you're using library, adds properties object prototype. prepare these, switch background array , create loop this:

for (var n = 0; n < background.length; n++) { image = new image(); (function (x) {image.onload = function() { ctx.drawimage(image, background[x].x,background[x].y, background[x].w, background[x].h, background[x].dx, background[x].dy, background[x].dw, background[x].dh); } }(n)); image.src = background[n].url; }

you can preserve background object, in case need check property beingness expected @ first line in for..in:

if (!background.hasownproperty(n)) continue;

javascript image html5 canvas

No comments:

Post a Comment