如何在JavaScript中调整图像大小和显示图像

如何在JavaScript中调整图像大小和显示图像,javascript,jquery,html,ajax,image,Javascript,Jquery,Html,Ajax,Image,我试图从通过ajax函数返回的路径列表(10个项目长)中读取图像,调整每个路径的大小,然后在页面上逐个显示。但是,下面的代码仅显示第一个图像(已调整大小),而不显示其他图像。我敢肯定,调整尺寸的工作,因为印刷尺寸看起来正确。下面是我的JavaScript代码: // Helper function function scaleSize(maxW, maxH, currW, currH){ var ratio = currH / currW; if(currW >= maxW

我试图从通过ajax函数返回的路径列表(10个项目长)中读取图像,调整每个路径的大小,然后在页面上逐个显示。但是,下面的代码仅显示第一个图像(已调整大小),而不显示其他图像。我敢肯定,调整尺寸的工作,因为印刷尺寸看起来正确。下面是我的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);
        }
    })
}
//Helper函数
函数缩放(maxW,maxH,currW,currH){
var比率=电流/电流;
如果(currW>=maxW&&ratio=maxH){
currH=最大值;
currW=电流/比率;
}
返回[当前,当前];
}
函数获取相似的图像(图像名称){
console.log(图像名称)
$.ajax({
类型:“POST”,
contentType:“应用程序/json;字符集=utf-8”,
url:“/get_-Simular”,
数据类型:“json”,
async:true,
数据:JSON.stringify({name:image_name}),
成功:功能(数据){
控制台日志(数据);
图像列表=数据['images']
类别=数据['category']

对于(var i=0;i您的代码中存在一些问题。
1) 图像宽度和高度是CSS属性,在
img.onload
处理程序中可能是
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
成功:函数(数据){
控制台日志(数据);
image_list=data.images;
category=data.category;

对于(var i=0;i您的代码中存在一些问题。
1) 图像宽度和高度是CSS属性,在
img.onload
处理程序中可能是
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
成功:函数(数据){
控制台日志(数据);
image_list=data.images;
category=data.category;

对于(var i=0;i如果我们将
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
是一个事件,这意味着它从代码异步运行。您正在使用新的图像元素(和新的
href
属性)更新
img
值在触发第一个
load
事件之前。因此
onload
事件实际上是在上次更新
img
变量后调用的,这实际上是在到达
for
的最后一个循环时发生的

为什么?

因为
for
循环不会为变量
img
创建新的作用域,所以每次触摸
img
var时,即使将
var
放在前面,原始
img
也会更新

然后应该使用函数,因为函数实际上为其中声明的变量(
var myVar
)创建了一个新的作用域:

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]);
}
函数大小(imageUrl){
var img=document.createElement(“img”);
img.src=imageUrl;
var-actualH;
var实际值;
var newH;
var newW;
img.onload=函数(){
实际宽度=此宽度;
实际高度=此高度;
var newSize=scaleSize(300,300,实际值,实际值);
this.width=newSize[0];
this.height=newSize[1];
document.getElementById('imageDiv').appendChild(img);
};
}
对于(变量i=0;i
如果我们简化您的
循环,如下所示:

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
是一个事件,这意味着它从代码异步运行。您正在使用新的图像元素(和新的
href
属性)更新
img
值在触发第一个
load
事件之前。因此
onload
事件实际上是在上次更新
img
变量后调用的,这实际上是在到达
for
的最后一个循环时发生的

为什么?

因为
for
循环不会为变量
img
创建新的作用域,所以每次触摸
img
var时,即使将
var
放在前面,原始
img
也会更新

然后应该使用函数,因为函数实际上为其中声明的变量(
var myVar
)创建了一个新的作用域:

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]);
}
函数大小(imageUrl){
var img=document.createElement(“img”);
img.src=imageUrl;
var-actualH;
var实际值;
var newH;
var newW;
img.onload=函数(){
实际宽度=此宽度;
实际高度=此高度;
var newSize=scaleSize(300,300,实际值,实际值);
this.width=newSize[0];
this.height=newSize[1];
document.getElementById('imageDiv').appendChild(img);
};
}
对于(变量i=0;i
欢迎使用SO!首先,您的
图像列表。长度是否大于1?是-长度为10个项目,当您记录
新闻大小时,您有预期的值(宽度和高度小于或等于300)?是,这里是前两个项目(旧尺寸和新尺寸)的输出示例:227 900[75.66666666300]380 583[195.54030874785593300]首先,您应该执行
返回[Math.round(currW),Math.round(currH)]
在您的
缩放
函数中,以避免出现奇怪的浮点数,即使它不能解决您的问题。欢迎这样做!首先,是您的
图像列表。长度是否大于1?是-长度为10个项目,当您记录
新闻缩放
时,您有预期的值(宽度和高度小于或等于300)?是,这是前两项(旧尺寸和新尺寸)的输出示例:227 900[75.666666300]380 58