JavaScript——动画原理
首先给“动画”进行定义:随时间的变化而改变某个元素在浏览器窗口中里的显示位置。
当物体在快速运动时, 当人眼所看到的影像消失后,人眼仍能继续保留其影像1/24秒左右的图像,这种现象被称为视觉暂留现象。是人眼具有的一种性质。人眼观看物体时,成像于视网膜上,并由视神经输入人脑,感觉到物体的像。但当物体移去时,视神经对物体的印象不会立即消失,而要延续1/24秒左右的时间,人眼的这种性质被称为“眼睛的视觉暂留”。
人眼不能分辨超过每秒30帧的画面。
从技术上讲,实现动画并不难,问题是在开发中应不应该使用动画。但是这些四处移动的元素一定要对用户有帮助,而不是让用户反感,这才是在网页中使用动画的最终目的。
比如,在一个页面中有一个小球,只要不断扩大左边距的值,就能实现移动的效果,如果这种效果时间间隔够小,使人眼不能察觉这个小球的抖动,这是就形成了一个动画。
下面就使一个小球向右移动的小例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>小球移动</title>
<style type="text/css">
#box {
width: 60px;
height: 60px;
border-radius: 50%;
background: gray;
position: absolute;
left: 0px;
}
#wall {
width: 3px;
height: 200px;
background: #f40;
position: absolute;
left: 800px;
}
</style>
</head>
<body>
<button id="stop">停止</button>
<button id="start">开始</button>
<div id="box"></div>
<!-- <div id="wall"></div> -->
<script type="text/javascript">
// var box = document.getElementById("box").style.width;//这种方法只能取出样式表中的样式,
//不能取出样式表中的样式,要想取出样式表中的样式,就要使用window.getComputedStyle方法。
// console.log(box);
var start = document.getElementById("start");
var speed = 5;
var stop = document.getElementById("stop");
var wall = document.getElementById("wall");
var box = document.getElementById("box");
// var wallWidth = parseInt(window.getComputedStyle(wall, null).left);
// console.log(wallWidth);
// console.log(stop);
var t;//定时器标号
var boxWidth = window.getComputedStyle(box, null).width;//使用window.getComputedStyle(,null)
//才能取出样式表中的样式。
// console.log(boxWidth);
boxWidth = parseInt(boxWidth);//把60px 转化成为数字60.
console.log(boxWidth);//60
// var leftMax = wallWidth - boxWidth;
// console.log(leftMax);//到达这个距离时停止移动。就是取消定时器。
start.onclick = function () {
clearInterval(t);
t = setInterval(moveRight, 20);
}
function moveRight() {
//不断的扩大左边距left的值就能实现动画 。
//left 撞墙时停止动画
box.style.left = speed + "px";//
speed += 5;
}
stop.onclick = function stopMove() {
clearInterval(t);
};
</script>
</body>
</html>
动画原理到此结束。