簡體   English   中英

如何在JavaScript中調整大小和顯示圖像

[英]How to resize and display images in JavaScript

我試圖從通過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);
        }
    })
}

您的代碼中存在一些問題。
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

如果我們簡化你的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事件之前,您將使用新的圖像元素(和新的href屬性)更新img值。 因此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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM