等比例缩放图片

js代码:

01 <script language=""javascript"" type=""text/javascript"">
02 <!--
03 // 说明:用 JavaScript 实现网页图片等比例缩放
04 // 整理:http://www.CodeBit.cn
05 function DrawImage(ImgD,FitWidth,FitHeight)
06 {
07 var image=new Image();
08 image.src=ImgD.src;
09 if(image.width>0 && image.height>0)
10 {
11 if(image.width/image.height>= FitWidth/FitHeight)
12 {
13 if(image.width>FitWidth)
14 {
15 ImgD.width=FitWidth;
16 ImgD.height=(image.height*FitWidth)/image.width;
17 }
18 else
19 {
20 ImgD.width=image.width;
21 ImgD.height=image.height;
22 }
23 }
24 else
25 {
26 if(image.height>FitHeight)
27 {
28 ImgD.height=FitHeight;
29 ImgD.width=(image.width*FitHeight)/image.height;
30 }
31 else
32 {
33 ImgD.width=image.width;
34 ImgD.height=image.height;
35 }
36 }
37 }
38 }
39 //-->
40 </script>

调用方式:

1 <img src=""1148202890.jpg"" alt=""自动缩放后的效果"" onload=""javascript:DrawImage(this,200,200);"" />

如果图片较大,建议在图片标签里面同时设置期望的图片大小,这样不会导致页面在加载中撑开,该大小不会影响最终缩放效果。可以修改上面的代码为:

1 <img src=""1148202890.jpg"" alt=""自动缩放后的效果"" width=""200"" height=""200""onload=""javascript:DrawImage(this,200,200);"" />
原文地址:https://www.cnblogs.com/Jlasp/p/3072385.html