图片按比例缩放js

JavaScript08

图片按比例缩放js,第1张

<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 onload="javascript:DrawImage(this,100,100)" src="" />

这个是把图片固定在宽和高各是100px,在这区间进行缩放。

图片按比例缩放

function DrawImage(Img,WIDTH,HEIGHT){

var image=new Image()

image.src=Img.src

width=WIDTH//预先设置的所期望的宽的值

height=HEIGHT//预先设置的所期望的高的值

if(image.width>width||image.height>height){//现有图片只有宽或高超了预设值就进行js控制

w=image.width/width

h=image.height/height

if(w>h){//比值比较大==>宽比高大

//定下宽度为width的宽度

Img.width=width

//以下为计算高度

Img.height=image.height/w

}else{//高比宽大

//定下宽度为height高度

img.height=height

//以下为计算高度

Img.width=image.width/h

}

}

}

<img src="xxxx" onload=javascript:DrawImage(this,290,215)>

一般来说,实现图片的放大缩小功能都用到了比较大的封装插件,特别是以jQuery插件居多,而实际上单纯实现对原图本身的放大缩小,用简单几行原生JS代码就可以做到。在今天分享的这个实例中,点击放大按钮不松鼠标,图片会不断的逐渐放大,当然也可以点一下放大一点,点击缩小按钮则反之,有需要的朋友可以考虑收藏备用哦

以下为全部代码:

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html charset=utf-8" />

        <title>javascript控制图片缩小或者放大</title>

    </head>

    <body>

        <script type="text/javascript">

            var oTime

            function changeSize(id,action){

             var obj=document.getElementById(id)

             obj.style.zoom=parseInt(obj.style.zoom)+(action=='+'?+10:-10)+'%'

             oTime=window.setTimeout('changeSize(\''+id+'\',\''+action+'\')',100)

            }

            document.onmouseup=function(){

             window.clearTimeout(oTime)

            }

        </script>

        <div style="height:350px overflow: auto">

        <img id="headImg" src="

        <button onmousedown="changeSize('headImg','+')" onmouseup="window.clearTimeout(oTime)">放大</button>

        <button onmousedown="changeSize('headImg','-')" onmouseup="window.clearTimeout(oTime)">缩小</button>

    </body>

</html>