【问题标题】:Inserting multiple image files into canvas将多个图像文件插入画布
【发布时间】:2013-06-04 12:11:56
【问题描述】:

我有下面的代码,它应该找到用户插入到 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);
        }   
    }

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

提前致谢!

【问题讨论】:

    标签: javascript html canvas drawimage


    【解决方案1】:

    您已将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);
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 2017-02-24
      • 2020-05-05
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 2019-10-17
      相关资源
      最近更新 更多