簡體   English   中英

Javascript錯誤:無法讀取null的屬性“ width”

[英]Javascript error: Cannot read property 'width' of null

我試圖獲取圖像上像素的顏色。 我在這里找到了代碼: 如何從圖像中獲取像素的x,y坐標顏色?

錯誤:

未捕獲的TypeError:無法讀取null的屬性“寬度”。

<canvas id="main"></canvas>    

<script>

    var img = document.getElementById("https://static.wixstatic.com/media/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png/v1/fill/w_980,h_735,al_c,usm_0.66_1.00_0.01/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png");
    var canvas = document.createElement("main");

    canvas.width = img.width;     //<-- error her
    canvas.height = img.height;

    pix = canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);







</script>

我試圖獲取圖像上像素的顏色。

錯誤:

未捕獲的TypeError:無法讀取null的屬性“寬度”。

看起來您想通過其src屬性選擇圖像 請改用querySelector因為您不太可能擁有帶有此id的圖像。

然后替換這條線

 var img = document.getElementById("https://static.wixstatic.com/media/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png/v1/fill/w_980,h_735,al_c,usm_0.66_1.00_0.01/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png");

通過

var img = document.querySelector("img[src='https://static.wixstatic.com/media/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png/v1/fill/w_980,h_735,al_c,usm_0.66_1.00_0.01/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png']");

這是因為您的script可能位於head或者圖像加載緩慢,因此在腳本運行后將其執行。

用這個:

    var img = new Image();
    img.src = "https://static.wixstatic.com/media/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png/v1/fill/w_980,h_735,al_c,usm_0.66_1.00_0.01/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png"
    img.onload = function(){
      var height = img.height;
      var width = img.width;

      // code here to use the dimensions
    }

您提供的是圖片的src屬性,而不是id

如果您的元素具有ID,則非常簡單,只需指定它即可:

var img = document.getElementById("yourImgId");

如果您的元素沒有ID,則建議您從JavaScript訪問它,然后在其中添加一個ID。

如果您的元素沒有ID,並且您無法添加它,請嘗試以下解決方案:

function getImgBySrc(src) {
    var allImages = document.getElementsByTagName("img");
    for(var i = 0; i < allImages.length; i++)
        if (allImages[i].src === src) {
            return allImages[i];
        }
    }
}

接着:

var img = getImgBySrc("https://static.wixstatic.com/media/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png/v1/fill/w_980,h_735,al_c,usm_0.66_1.00_0.01/50592f_dca6acd5bb474e61b306e1969e7e8f66~mv2_d_2339_1654_s_2.png");

canvas.width = (img && img.width) || 200; // Provide a default width if image was not found
canvas.height = (img && img.height) || 400; // Provide a default height if image was not found

暫無
暫無

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

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