紫悦博客

不进则退,退一步万丈悬崖!

0%

JS处理图片变形问题

<img src="http://www.baidu.com/img/bdlogo.gif" onload="proDownImage(this)" width="100" height="100">
<script type="text/javascript">
var proMaxWidth = 100;
var proMaxHeight = 100;
function proDownImage(ImgD,width,height){
    ImgD.width = "";
    ImgD.height = "";
    ImgD.style.marginLeft = 0;
    ImgD.style.marginTop = 0;
    var image=new Image();
    image.src=ImgD.src;
    proMaxWidth = width ? width : proMaxWidth;
    proMaxHeight = height ? height : proMaxHeight;
    if(image.width>0 && image.height>0){
        var rate = (proMaxWidth/image.width < proMaxHeight/image.height)?proMaxWidth/image.width:proMaxHeight/image.height;
        if(rate <= 1){ 
            ImgD.width = image.width*rate;
            ImgD.height =image.height*rate;
        }else {
            ImgD.width = image.width;
            ImgD.height =image.height;
        }
        if(ImgD.width < proMaxWidth){
            var w = (proMaxWidth-ImgD.width)/2;
            ImgD.style.marginLeft=w+'px';
        }
        if(ImgD.height < proMaxHeight){
            var h = (proMaxHeight-ImgD.height)/2;
            ImgD.style.marginTop=h+'px';
        }
    }
}
</script>