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

  • 相关阅读:
    __cdecl, __stdcall, __fastcall,__pascal调用区别
    Windows Hook原理与实现
    C语言四大存储区域总结
    MFC DestroyWindow、OnDestroy、OnClose 程序关闭相关
    VC++动态链接库DLL编程深入浅出"
    windows 安全模型简介
    获取当前焦点窗口进程名
    获取IE URL
    DLL编写中extern “C”和__stdcall的作用
    Django2支持跨域方法
  • 原文地址:https://www.cnblogs.com/CCHUncle/p/6252597.html
Copyright © 2011-2022 走看看