js获取图片原始比例并根据容器大小,图片比例缩放图片的宽高值

js获取图片原始比例并根据容器大小,图片比例缩放图片的宽高值
以下为具体方法代码:

//图片缩放横纵比
//imgWidth:图片宽, imgHeight:图片高, containerWidth:容器宽, containerHeight:容器高
function imageScaling (imgWidth:number, imgHeight:number, containerWidth:number, containerHeight:number) {
    
    
    let tempWidth = 0, tempHeight = 0;

    if (imgWidth > 0 && imgHeight > 0) {
    
    
        //原图片宽高比例 大于 指定的宽高比例,这就说明了原图片的宽度必然 > 高度
        if (imgWidth / imgHeight >= containerWidth / containerHeight) {
    
    
            if (imgWidth > containerWidth) {
    
    
                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}
}

猜你喜欢

转载自blog.csdn.net/qq_37656005/article/details/125745349