通过js等比扩大图片的比例
在做web开发的时候,显示图片是经常用到。在默认的情况下图片是扩充,但是有的时候显示效果会不如人意。有时容器的大小是固定的,我们要把图片等比扩大。
下面通过js来简单的实现图片等比扩大。
var imgObj = new Image(); //
图片对象
imgObj.src = "d:\linuxborder.jpg" ; //
图片地址
imgwidth = imgObj.width; // 图片宽
imgheight = imgObj.height; //
图片高
document.all("myimg").width = imgwidth * rate; //
改变图片宽
document.all("myimg").height = imgheight * rate; //改变图片高
“myimg”是<img name="myimg">中的name
事例代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body onload = changesize()>
<center> images:
<table border="1" width="445" height="140" bordercolor="#FF6600" cellSpacing=0 cellPadding=0>
<HR style="border:1 dashed green" width="100%" SIZE=4>
<tr>
<td>
<p align="center">
<img name="myimg" src="d:\linuxborder.jpg" width="440" height="140"></p>
</td>
</tr>
</table>
</center>
</body>
<script language="javascript" type="text/javascript">
function changesize(){
var imgwidth;
var imgheight;
var imgObj = new Image(); //
图片对象
var tempwidth;
var tempheight;
var rate; // 扩大率
imgObj.src = "d:\linuxborder.jpg" ; // 图片地址
imgwidth = imgObj.width; //
图片宽
imgheight = imgObj.height; //
图片高
tempwidth = 440 - imgwidth;
tempheight = 140 - imgheight;
if(tempwidth < tempheight) {
rate = 440 / imgwidth ;
} else {
rate = 140 / imgheight;
}
document.all("myimg").width = imgwidth * rate; //改变图片宽
document.all("myimg").height = imgheight * rate; //改变图片高
}
</script>
</html>