JS按比例缩放图片
1、JS代码
1 <script type="text/javascript" language="javascript"> 2 var flag = false; 3 function DrawImage3(iwidth,iheight,ImgD) { 4 var image = new Image(); 5 image.src = ImgD.src; 6 if (image.width > 0 && image.height > 0) { 7 flag = true; 8 //原图宽除高的值和定义宽除高的值的比较 9 if (image.width / image.height >= iwidth / iheight) { 10 // 原图的宽大于定义的宽 11 if (image.width > iwidth) { 12 ImgD.width = iwidth; 13 //定义的宽度和原图的宽度的比例,同比缩小高度 14 ImgD.height = (image.height * iwidth) / image.width; 15 } else { 16 ImgD.width = image.width; 17 ImgD.height = image.height; 18 } 19 ImgD.alt = image.width + "×" + image.height; 20 } 21 else { 22 // 原图的高大于定义的高 23 if (image.height > iheight) { 24 ImgD.height = iheight; 25 //定义的高度和原图的高度的比例,同比缩小宽度 26 ImgD.width = (image.width * iheight) / image.height; 27 } else { 28 ImgD.width = image.width; 29 ImgD.height = image.height; 30 } 31 ImgD.alt = image.width + "×" + image.height; 32 } 33 } 34 } 35 </script>
2、前代代码
1 <img alt='' src="Image/wuqilong.jpg" onload="DrawImage3(200,150,this)" />