首頁  >  問答  >  主體

使用 JavaScript 限製圖像比例

<input type="file" id="file" accept="image/gif, image/jpeg, image/png">

HTML 程式碼的結構如下。 在這種情況下,如果輸入中沒有輸入比例為1:1的圖像,我想透過JavaScript移動到另一個頁面。

P粉111927962P粉111927962244 天前435

全部回覆(1)我來回復

  • P粉032977207

    P粉0329772072024-02-18 10:46:13

    您基本上需要為輸入添加一個處理程序,並檢查 height/width === 1 ,您可以使用此函數來驗證它:

    const fileUpload = document.getElementById("file");
    
    function validateImage(target) {
      const reader = new FileReader();
      reader.readAsDataURL(fileUpload.files[0]);
      reader.onload = function (e) {
    
        const image = new Image();
        image.src = e.target.result;
    
        image.onload = function () {
          const height = this.height;
          const width = this.width;
          
          if (height / width !== 1) {
            console.log("ASPECT RATIO NOT 1:1");
            window.location.href = "#otherpage"; // redirect
            return false;
          }
          
          // do nothing
          return true;
        };
      };
    }

    回覆
    0
  • 取消回覆