JavaScript實現網頁圖片等比例自動縮放函數 DrawImag
發表日期:2015-10-31 文章編輯:南昌開優網絡 瀏覽次數:4249 標簽:JS應用
在Web上顯示圖片,通常都會有圖片顯示比例問題,如果不給<img />限制width和height,那么如果圖片大了就會將整個頁面擠亂,圖片小了又會使圖片失真。
我的需求如下:
1、預先定義好圖片顯示的標準寬度和高度。
2、如果圖片的大小超過了標準定義,那么等比例壓縮圖片。
3、如果圖片的大小等于標準定義,那么按照標準寬度和高度顯示圖片。
4、如果圖片的大小小于標準定義,那么不對圖片進行任何壓縮處理。
<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 src="images/toplogo.gif" onload="javascript:DrawImage(this,100,100)">