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

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

  如果在网上我们发现图片太小,看不清该怎么办?当然是放大啊,放大有很多种方式,这里介绍其中比较简单的一种。

  我们可以通过点击按钮放大和缩小图片,每次都会按照相同的倍数,并且不会无限放大和缩小,如果达到了最值,会由相应的提示。先看以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>自制缩放</title>
	<style>
		#wrapper{
			 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>

  这里的JavaScript代码最需要理解的有以下几点:

  1. 使用window.onload是因为虽然我们已经把script标签放到了内容的最下面,即html页面下载完成之后在执行脚本代码,但是图片有可能未加载完全,使用window.onload()更加保险。
  2. 在页面加载完成之后会从上到下地执行script中的代码,对于声明变量则会得到固定的值,比如maxWidth maxHeight minWidth minHeight这些变量的值自始至终都是固定的,因为这些语句只执行了一遍,而函数声明内的变量在调用函数之前是不会被赋值的。
  3. 对于计时器setInterval我们必须将它赋值给一个变量,这是为了在达到我们的要求之后可以用clearInterval将计时器停止。
  4. 刚刚说到,maxWidth maxHeight minWidth minHeight这些变量的值都是固定的,因为它们所在的声明语句只被执行一遍。而对于endWidth endHeight却是动态变化的,这个需要格外注意。

最终效果如下:

A原始大小图片

B放大图片

C.放大到不能继续

D.缩小图片

E.缩小到不能再小图片

    

原文地址:https://www.cnblogs.com/zhuzhenwei918/p/6034512.html