zoukankan      html  css  js  c++  java
  • JS实现图片宽高的等比缩放

    关于图片宽高的等比缩放,其实需求就是让图片自适应父容器的宽高,并且是等比缩放图片,使图片不变形。

    例如,需要实现如下的效果:

    要实现上面的效果,需要知道图片的宽高,父容器的宽高,然后计算缩放后的宽高。

    首先,图片的宽高和父容器的宽高都能方便的获取到,然后,等比缩放的算法如下:

     1 function scalingImage(imgWidth, imgHeight, containerWidth, containerHeight) {
     2     var containerRatio = containerWidth / containerHeight;
     3     var imgRatio = imgWidth / imgHeight;
     4 
     5     if (imgRatio > containerRatio) {
     6         imgWidth = containerWidth;
     7         imgHeight = containerWidth / imgRatio;
     8     } else if (imgRatio < containerRatio) {
     9         imgHeight = containerHeight;
    10         imgWidth = containerHeight * imgRatio;
    11     } else {
    12         imgWidth = containerWidth;
    13         imgHeight = containerHeight;
    14     }
    15 
    16     return {  imgWidth, height: imgHeight };
    17 }

    接着,如何让图片居中显示呢?

    方法一:可以设置img标签的margin-left和margin-top属性实现,这个可用通过父容器的宽高和图片缩放后的宽高计算出来。如下:

        var marginLeft = (containerWidth - width) / 2;
        var marginTop = (containerHeight - height) / 2;

    方法二:通过设置父容器的height和line-height属性值相同,以及img标签属性 vertical-align: middle; ,让img标签垂直居中;设置父容器属性 text-align: center; ,让img标签水平居中。

    如何让图片加载完成就自适应宽高呢?

    这个可以绑定img标签的onload事件,代码如下:

        <div class="img-container">
            <img src="images/1.png" onload="scalingImg(this)" width="" height="">
        </div>
     1 function scalingImg(obj){
     2     var $this = $(obj);
     3 
     4     var imgWidth=$this.width();
     5     var imgHeight=$this.height();
     6 
     7     var parent = $this.parent();
     8     var containerWidth = parent.width();
     9     var containerHeight=parent.height();
    10 
    11     var containerRatio = containerWidth / containerHeight;
    12     var imgRatio = imgWidth / imgHeight;
    13 
    14     if (imgRatio > containerRatio) {
    15         imgWidth = containerWidth;
    16         imgHeight = containerWidth / imgRatio;
    17     } else if (imgRatio < containerRatio) {
    18         imgHeight = containerHeight;
    19         imgWidth = containerHeight * imgRatio;
    20     } else {
    21         imgWidth = containerWidth;
    22         imgHeight = containerHeight;
    23     }
    24 
    25     $this.attr('width',imgWidth);
    26     $this.attr('height',imgHeight);
    27 }

    最后,附上demo源码如下:ScaleImageDemo.zip

  • 相关阅读:
    全国计算机等级考试二级教程-C语言程序设计_第10章_字符串
    网易云课堂_程序设计入门-C语言_第六章:数组_2鞍点
    arcgis api for silverlight开发系列之二:缓存图层与动态图层及图层总结 .
    VS2010程序打包操作(超详细的)
    地图三要素
    创业建议
    写代码时,必须注意“异常处理”
    WPF——RenderTransform特效
    MVVM特点、源(数据)与目标(如:控件等)的映射
    使用触发器定义 WPF 控件的行为
  • 原文地址:https://www.cnblogs.com/CCHUncle/p/6252597.html
Copyright © 2011-2022 走看看