zoukankan      html  css  js  c++  java
  • 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}
    }

     

  • 相关阅读:
    sql server获取指定库下的所有表名
    sql根据字符将一行拆成多行
    刷题416. Partition Equal Subset Sum
    刷题394. Decode String
    刷题347. Top K Frequent Elements
    刷题309. Best Time to Buy and Sell Stock with Cooldown
    刷题338. Counting Bits
    刷题337. House Robber III
    刷题312. Burst Balloons
    刷题621. Task Scheduler
  • 原文地址:https://www.cnblogs.com/zxuedong/p/13384406.html
Copyright © 2011-2022 走看看