0

我有下面的代码,它应该找到用户插入到 div 中的图像,当他单击“捕捉”按钮时,它将这些图像安装到画布对象内的一个图像中。美好的。我可以在画布内找到图像、位置和调整大小,但图像源始终来自找到的最后一张图像。请问有人可以帮我分析这段代码吗?

提前致谢。

<!-- 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);
        }   
    }

再一次:一切正常;除了图像的来源,它总是获取 #content div 中的最后一个图像来源。

提前致谢!

4

1 回答 1

2

您已创建base_image为全局变量,因此每次通过函数都会更新相同的引用。在函数中第一次使用的前面添加var关键字dIm()

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);
    }   
}
于 2013-06-03T22:19:23.190 回答