使用计时器实现图片的准确缩放

Posted 张松任

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用计时器实现图片的准确缩放相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自制缩放</title>
    <style>
        #wrapper{
            width: 500px;
            margin: 0 auto;
            position: relative;
        }
        #input{
            position: absolute;
            top: 0px;
        }
        input{
            color:green;
            background: white;
        }
    </style>
</head>
<body>
    <div id="wrapper">
        <div id="input">
            <input  type="button" value="放大" id="enlarge"><input type="button" value="缩小" id="narrow">
        </div>
        <img src="4.jpg" alt="this is a picture" id="myImage">
    </div>
    <script>
    window.onload=function(){
        var image=document.getElementById("myImage");
        var largeButton=document.getElementById("enlarge");
        largeButton.onclick=function(){
            larger();
        }
        var maxWidth=image.width*2.5;
        var maxHeight=image.height*2.5;
        function larger(){
            var endHeight=image.height*1.3;
            var endWidth=image.width*1.3;
            var largeTimer=setInterval(function(){
                if(image.width<endWidth){
                    if(image.width<maxWidth){
                        image.width=image.width*1.03;
                        image.height=image.height*1.03;
                    }else{
                        alert("此图片已经放到了最大。");
                        clearInterval(largeTimer);
                    }
                }else{
                    clearInterval(largeTimer);
                }
            },80);
        }
        var smallButton=document.getElementById("narrow");
        smallButton.onclick=function(){
            smaller();
        }
        var minWidth=image.width*0.5;
        var minHeight=image.height*0.5;
        function smaller(){
            var endWidth=image.width*0.7;
            var endHeight=image.height*0.7;
            var smallTimer=setInterval(function(){
                if(image.width>endWidth){
                    if(image.width>minWidth){
                        image.width=image.width*0.95;
                        image.height=image.height*0.95;
                    }else{
                        alert("此图片已经缩到了最小");
                        clearInterval(smallTimer);
                    }
                }else{
                    clearInterval(smallTimer);
                }
            },130);
        }
    }
    </script>
</body>
</html>

以上是关于使用计时器实现图片的准确缩放的主要内容,如果未能解决你的问题,请参考以下文章

如何准确延长微小视频片段的持续时间?

点击按钮,缩放图片(img.widthimg.style.widthimg.offsetWidth)

Qt 的插入的图片的移动、缩放操作

python使用上下文对代码片段进行计时,非装饰器

前端怎么实现点击图片将图片放大而且图片可以手势随意缩放,最好附上代码,非常感谢

实现高分辨率计时器的最佳方法