图片按比例缩放js

JavaScript06

图片按比例缩放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)>

用js控制图片额大小。主要是修改图片的宽度和高度。下面是简单的代码实现:

HTML 代码:

<img src='../1.jgp' id='img' />

这个时候img的图片自身是多大,就会显示多大。100px*100px的图。

js代码:

var oImg = document.getElementById('img')

oImg.width = '50px' //当给img标签的宽度设置为50px后,高度会自动按比例缩小。

oImg.width = '200px' //当给img标签的宽度设置为200px后,高度会自动按比例扩大。