我试图从通过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!首先,你的'image_list.length'大于1? –
是的,它有10个项目长 – Melanie
当你记录'newSize'时,你有期望值(宽度和高度小于或等于300)? –