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);
}
})
}
에 오신 것을 환영합니다 SO에 : 함수가 실제로 내부에 선언 된 변수에 대한 새 범위 (
var myVar
)을 생성하기 때문에그런 다음 함수를 사용한다! 첫째,'image_list.length'가 1보다 큰가요? –
네 - 길이가 10입니다. – Melanie
그리고'newSize'를 로그 할 때 예상 값 (너비와 높이가 300보다 작거나 같음)이 있습니까? –