JavaScript實(shí)現(xiàn)網(wǎng)頁圖片等比例自動縮放函數(shù) DrawImag
發(fā)表日期:2015-10-31 文章編輯:南昌開優(yōu)網(wǎng)絡(luò) 瀏覽次數(shù):4263 標(biāo)簽:JS應(yīng)用
在Web上顯示圖片,通常都會有圖片顯示比例問題,如果不給<img />限制width和height,那么如果圖片大了就會將整個頁面擠亂,圖片小了又會使圖片失真。
我的需求如下:
1、預(yù)先定義好圖片顯示的標(biāo)準(zhǔn)寬度和高度。
2、如果圖片的大小超過了標(biāo)準(zhǔn)定義,那么等比例壓縮圖片。
3、如果圖片的大小等于標(biāo)準(zhǔn)定義,那么按照標(biāo)準(zhǔn)寬度和高度顯示圖片。
4、如果圖片的大小小于標(biāo)準(zhǔn)定義,那么不對圖片進(jìn)行任何壓縮處理。
<script language="JavaScript">
<!--
//圖片按比例縮放
var flag=false;
function DrawImage(ImgD,iwidth,iheight){
//參數(shù)(圖片,允許的寬度,允許的高度)
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>
調(diào)用:<img src="images/toplogo.gif" onload="javascript:DrawImage(this,100,100)">