JAVA、PHP、前端、APP、网站开发 - 开发技术学习

开发技术学习 » 前端设计 » js中间截取等比例缩小的图片,防止图片变形,js图片上下居中

js中间截取等比例缩小的图片,防止图片变形,js图片上下居中

今天 在修改 爱琴海婚纱 网站的时候,有一个相当于相册的地方要求修改, 以前图片变形,上下不居中。 很多地方都要用到图片上下居中的,这里查找 了一个js 的function供大家研究 /** * 根据要求的大小来判断,等比例截取原始图片 * 在各个浏览器都看了一下,都支持这个Image() **/ //图片按比例缩放 var flag=false; function DrawImage(ImgD,iwidth,iheight){ //参数(图片,允许的宽度,允许的高度) var image=new Image(); image.src=ImgD.src; if(image.width > 0 && image.height > 0){ flag=true; if(image.width/image.height >= iwidth/iheight){ if(image.width>iwidth){ ImgD.width=iwidth; ImgD.height=(image.height*iwidth)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } ImgD.style.marginTop = (iheight - ImgD.height) / 2 + 'px'; ImgD.alt = "点击查看详情"; } else{ if(image.height>iheight){ ImgD.height=iheight; ImgD.width=(image.width*iheight)/image.height; }else{ ImgD.width=image.width; ImgD.height=image.height; } ImgD.style.marginTop = (iheight - ImgD.height) / 2 + 'px'; ImgD.alt = "点击查看详情"; } } } 调用方法: 这里结合相册效果非常好!

站点声明:部分内容源自互联网,为传播信息之用,如有侵权,请联系我们删除。

© Copyright 2011-2024 www.kfju.com. All Rights Reserved.
超级字帖 版权所有。蜀ICP备12031064号