将多个图像文件插入画布

Inserting multiple image files into canvas

本文关键字:插入 文件 图像      更新时间:2023-09-26

我有下面的代码,应该找到用户插入到div中的图像,当他单击"snap"按钮时,它将这些图像装入画布对象内的一个图像。很好。我可以在画布内找到图像,位置和调整大小,但图像源总是来自最后找到的图像。有人能帮我分析一下这段代码吗?

提前感谢。

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

再说一遍:一切都很好;除了图片源,它总是在#contentdiv中获取最后一个图片源。

提前感谢!

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

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