2013-06-03 3 views
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 내부의 마지막 이미지 소스를 항상 가져 오는 이미지 소스는 제외됩니다.

미리 감사드립니다.

답변

2

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