2016-06-19 2 views
1

ajax 함수를 통해 반환 된 경로 목록 (10 개 항목)에서 이미지를 읽으려고 시도하고 각각의 크기를 조정 한 다음 페이지에서 차례로 표시합니다. 그러나 아래 코드는 첫 번째 이미지 (크기 조정) 만 표시하고 다른 이미지는 표시하지 않습니다. 인쇄 된 크기가 올바르게 보이는 것처럼 크기 조정 작업이 제대로 수행되고 있는지 확신합니다. 아래 JavaScript 코드입니다 :JavaScript에서 이미지 크기를 조정하고 표시하는 방법

// Helper function 
function scaleSize(maxW, maxH, currW, currH){ 
    var ratio = currH/currW; 
    if(currW >= maxW && ratio <= 1) { 
     currW = maxW; 
     currH = currW * ratio; 
    } else if(currH >= maxH) { 
     currH = maxH; 
     currW = currH/ratio; 
    } 
    return [currW, currH]; 
} 

function get_similar_images(image_name) { 
    console.log(image_name) 
    $.ajax({ 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     url: "/get_similar", 
     dataType: "json", 
     async: true, 
     data: JSON.stringify({name: image_name}), 
     success: function(data) { 
      console.log(data); 
      image_list = data['images'] 
      category = data['category'] 
      for (var i=0; i<image_list.length; i++) { 
       var img = document.createElement("img"); 
       img.src = "static/products/"+category+"/"+image_list[i]; 
       var actualH; 
       var actualW; 
       var newH; 
       var newW; 
       img.onload = function(){ 
        actualW = this.width; 
        actualH = this.height; 
        console.log(actualW, actualH) 
        var newSize = scaleSize(300, 300, actualW, actualH); 
        console.log(newSize) 
        img.width = newSize[0]; 
        img.height = newSize[1]; 
        document.getElementById('imageDiv').appendChild(img) 
       }; 
      } 
     }, 
     error: function(xhr, status, error) { 
      // console.log(xhr.responseText); 
     } 
    }) 
} 
+0

에 오신 것을 환영합니다 SO에 : 함수가 실제로 내부에 선언 된 변수에 대한 새 범위 (var myVar)을 생성하기 때문에

그런 다음 함수를 사용한다! 첫째,'image_list.length'가 1보다 큰가요? –

+0

네 - 길이가 10입니다. – Melanie

+0

그리고'newSize'를 로그 할 때 예상 값 (너비와 높이가 300보다 작거나 같음)이 있습니까? –

답변

0

우리는 그런 당신의 for 루프를 단순화 경우

var img = document.createElement("img"); 
img.src = image_list[0]; 
img.onload = function() { 
    console.log(img); 
}; 

var img = document.createElement("img"); 
img.src = image_list[1]; 
img.onload = function() { 
    console.log(img); 
}; 

당신의 실수가 어디에서 오는지 당신은 이해할 것이다. onload은 이벤트이므로 비동기 적으로 코드에서 실행됩니다. 첫 번째 load 이벤트가 트리거되기 전에 img 값을 새 이미지 요소 (및 새 href 특성)로 업데이트합니다. 따라서 onload 이벤트는 실제적으로 의 마지막 루프에 도달했을 때 실제로 발생하는 img 변수의 최종 업데이트 이후에 호출됩니다.

왜?

for 루프 변수 img의 새로운 범위를 만들지 않습니다, 그래서 당신은 앞에 var을 두는 경우에도 때마다 당신의 img var에 접촉하기 때문에, 원래 img가 업데이트됩니다.

function injectAndResize(imageUrl) { 
    var img = document.createElement("img"); 
    img.src = imageUrl; 
    var actualH; 
    var actualW; 
    var newH; 
    var newW; 
    img.onload = function() { 
    actualW = this.width; 
    actualH = this.height; 
    var newSize = scaleSize(300, 300, actualW, actualH); 
    this.width = newSize[0]; 
    this.height = newSize[1]; 
    document.getElementById('imageDiv').appendChild(img); 
    }; 
} 

for (var i = 0; i < image_list.length; i++) { 
    injectAndResize(image_list[i]); 
} 
+0

이것이 효과적입니다! 감사합니다. 당신을 도와주세요! – Melanie

+0

환영합니다 ^^ –

0

코드에 몇 가지 문제점이 있습니다.
1) 이미지 너비와 높이는 CSS 속성이며 핸들러에서는 undefined 일 수 있습니다. 대신 this.naturalWidth을 사용하십시오.
2) img.src = 'url';이 이미지로드를 유발합니다.img.onload 뒤에 을 입력하십시오.

success: function(data) { 
     console.log(data); 
     image_list = data.images; 
     category = data.category; 
     for (var i=0; i<image_list.length; i++) { 
      var img = document.createElement("img"); 
      img.onload = function(){ 
       var actualW = this.naturalWidth; 
       var actualH = this.naturalHeight; 
       console.log(actualW, actualH) 
       var newSize = scaleSize(300, 300, actualW, actualH); 
       console.log(newSize) 
       this.width = newSize[0]; 
       this.height = newSize[1]; 
       //also think what to do with images which are already there 
       //probably remove 
       document.getElementById('imageDiv').appendChild(this) 
      };//img.onload 
      img.src = "static/products/"+category+"/"+image_list[i]; 
     }//for 
    },//success 
관련 문제