图片按比例缩放js

JavaScript020

图片按比例缩放js,第1张

<script language="JavaScript">

<!--

//图片按比例缩放

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.alt=image.width+"×"+image.height

}

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.alt=image.width+"×"+image.height

}

}

}

//-->

</script>

调用的时候

<img onload="javascript:DrawImage(this,100,100)" src="" />

这个是把图片固定在宽和高各是100px,在这区间进行缩放。

原理:

用JS在加载图片后判断图片是否突破规定的高和宽,如果超过再根据图片的宽高比例进行调整。

特别说明,JS代码只限制图片的高或者宽时,宽或者高会按照比例进行相应调整。

假如你需要把所有的图片显示在140*226的区间里面,那么就使用下面这样的代码:

<img src=2009/04/1232336585-19.jpg onload='if (this.width>140 || this.height>226) if (this.width/this.height>140/226) this.width=140else this.height=226'>

<html>

<head>

<style>

html,body{width:100%height:100%margin:auto 0pxpadding:auto 0pxtext-align:center}

.imgBox, .imgBox img{width:100%height:100%}

</style>

</head>

<body>

<div class="imgBox">

<img src="1.jpg" />

</div>

</body>

</html>

如上代码可以实现,把图片换一下就OK了,希望可以帮到你。