Reputation: 621
I have the code below which is supposed to find the images the user inserted into a div and when he clicks the "snap" button, it mounts those images into one image inside a canvas object. Fine. I can find the images, position and resize inside the canvas, but the image source is always coming from the last image found. Please can someone help me analyse this chunk of code?
Thanks in advance.
<!-- The HTML -->
<div id="content" style="width: 640px; height: 480px;">
<div class="dragable-div"><img class="resizeable-image" style="position:absolute" src="images/glasses.gif" width="200" height="180" /></div>
<div class="dragable-div"><img class="resizeable-image" style="position:absolute" src="images/nordic.gif" width="100" height="100" /></div>
</div>
<!-- The JS wich recognizes the images and sends them into the canvas -->
$('#snap').click(function() {
len = $('#content > div').length;
for(i = 0; i < len; i++){
<!-- One '> div' more because the resize method puts one div around the object -->
ptop = $('#content > div > div').eq(i).offset().top-8;
pleft = $('#content > div > div').eq(i).offset().left - 8;
ih = $('#content > div > div').eq(i).height();
iw = $('#content > div > div').eq(i).width();
img = $('#content > div > div').eq(i).find('img').attr('src');
dIm(img, pleft, ptop, iw, ih);
}
});
function dIm(img_source, posLeft, posTop, imWid, imHei){
base_image = new Image();
base_image.src = img_source;
base_image.onload = function(){
context.drawImage(base_image, posLeft, posTop, imWid, imHei);
}
}
Once again: everything works just fine; except for the source of the images, which always gets the last image source inside the #content div.
Thanks in advance!
Upvotes: 0
Views: 201
Reputation: 75707
You've created base_image
as a global variable so each pass through the function is updating the same reference. Add the var
keyword in front of the first use in your dIm()
function.
function dIm(img_source, posLeft, posTop, imWid, imHei){
var base_image = new Image();
base_image.src = img_source;
base_image.onload = function(){
context.drawImage(base_image, posLeft, posTop, imWid, imHei);
}
}
Upvotes: 2