js計算圖片等比例縮放


js計算圖片等比例縮放

 

1.介紹:可以計算圖片和父容器的寬和高實現等比例的縮放

// 新建一個utils.js文件來放置這個工具函數

export function imgScaling (imgWidth, imgHeight, containerWidth, containerHeight) {
  let [
    // 用於設定圖片的寬和高
    tempWidth,
    tempHeight,
  ] = [
    undefined,
    undefined
  ]
  try {
    imgWidth = parseFloat(imgWidth)
    imgHeight = parseFloat(imgHeight)
    containerWidth = parseFloat(containerWidth)
    containerHeight = parseFloat(containerHeight)
  } catch (error) {
    throw new Error('抱歉,我只接收數值類型或者可以轉成數值類型的參數')
  }

  if (imgWidth > 0 && imgHeight > 0) {
    //原圖片寬高比例 大於 指定的寬高比例,這就說明了原圖片的寬度必然 > 高度
    if (imgWidth / imgHeight >= containerWidth / containerHeight) {
      if (imgWidth > containerWidth) {
        // alert('aaaaaaaa')
        tempWidth = containerWidth
        // 按原圖片的比例進行縮放
        tempHeight = (imgHeight * containerWidth) / imgWidth
      } else {
        // 按照圖片的大小進行縮放
        tempWidth = imgWidth
        tempHeight = imgHeight
      }
    } else {  // 原圖片的高度必然 > 寬度
      if (imgHeight > containerHeight) {

        tempHeight = containerHeight
        // 按原圖片的比例進行縮放
        tempWidth = (imgWidth * containerHeight) / imgHeight
      } else {
        // 按原圖片的大小進行縮放
        tempWidth = imgWidth
        tempHeight = imgHeight
      }
    }
  }

  return { tempWidth,  tempHeight}
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM