0

I need to draw a list of images that are being downloaded. Here is the code I have:

function drawCanvasImages(drawList) {
    for (var i in drawList) {
        var dl = drawList[i];
        var img = new Image;
        img.onload = function () {
            var ctx = $(dl.id).getContext('2d');
            ctx.drawImage(img, 0, 0);
        }
        img.src = dl.filename;
    }
}

The parameter is an array of structures that are {id: string, filename: string} Id is the jquery selector for the cavas, filename is the url of the image to show.

The problem is that in the onload function dl refers to the dl from the last trip around the for loop, whereas I need the a value for that particular trip around. I know I need to make a copy or some such thing, but I am not sure what the best practice here is.

Can you offer a recommendation?

Fraser Orr
  • 361
  • 1
  • 3
  • 19
  • Btw, [don't use `for in` enumerations on arrays](https://stackoverflow.com/q/500504/1048572) – Bergi Nov 03 '14 at 21:33
  • use drawList.forEach() instead of a for-loop to avoid these headaches. – dandavis Nov 03 '14 at 21:34
  • You seem to know the term "closure". Don't you know how exactly it works, or what problems do you have with applying this solution? – Bergi Nov 03 '14 at 21:34

0 Answers0