I’m rendering my Backbone model by appending to an element x canvases. Then in a loop I’m drawing an image on each one.
The Problem:
Only the last canvas seems to be drawn, the rest are left blank.
Here’s the code:
http://pastie.org/private/bt4b4imwd6csrv32gay2yq – render function
And here’s the model:
http://pastie.org/private/mvmlbrefzbcgltwyfyfw
I’ve outputted the image’s source and the actual canvas’s id in the onload event and I get only the last one (last canvas id, last image source) for x times (x = length of parts variable).
Thanks.
This is a “closure in a loop” issue. With your .onload you are creating a closure. This closure has access to its surrounding scope, but not at the time of its creation but rather at the time of its execution. And at that point of time the loop has reached the last element, so
faceImgandctxFacewill only have a reference to the last image.Solution: Create an inner closure with an immediately executed anonymous function, hand over the current
faceImgandctxFacein each loop and return an anonymous function that will be executed onload