图片按比例缩放js

JavaScript010

图片按比例缩放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,在这区间进行缩放。

图片按比例缩放

function DrawImage(Img,WIDTH,HEIGHT){

var image=new Image()

image.src=Img.src

width=WIDTH//预先设置的所期望的宽的值

height=HEIGHT//预先设置的所期望的高的值

if(image.width>width||image.height>height){//现有图片只有宽或高超了预设值就进行js控制

w=image.width/width

h=image.height/height

if(w>h){//比值比较大==>宽比高大

//定下宽度为width的宽度

Img.width=width

//以下为计算高度

Img.height=image.height/w

}else{//高比宽大

//定下宽度为height高度

img.height=height

//以下为计算高度

Img.width=image.width/h

}

}

}

<img src="xxxx" onload=javascript:DrawImage(this,290,215)>