在Web开发中,动画效果是非常重要的。本文将讲解Javascript中的匀速动画和缓冲动画的实现原理及示例说明。
在匀速动画中,物体的速度保持不变,让物体的移动更加平滑。
匀速动画的实现过程分为三个步骤:
代码实现如下:
function move(element, target, duration){
var start = parseFloat(getComputedStyle(element).left);
var distance = target - start;
var speed = distance / duration;
var interval = 10;
var timer = setInterval(function(){
var current = parseFloat(getComputedStyle(element).left);
if (Math.abs(current - target) <= Math.abs(speed)) {
clearInterval(timer);
element.style.left = target + 'px';
} else {
element.style.left = current + speed + 'px';
}
}, interval);
}
下面是一个匀速动画的示例,点击开始按钮后,红色的盒子会匀速从左边移动到右边。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>匀速动画示例</title>
<style>
#box {
position: absolute;
left: 0;
top: 100px;
width: 50px;
height: 50px;
background: red;
}
</style>
</head>
<body>
<div id="box"></div>
<button onclick="move(document.getElementById('box'), 500, 3000)">开始</button>
<script>
function move(element, target, duration){
var start = parseFloat(getComputedStyle(element).left);
var distance = target - start;
var speed = distance / duration;
var interval = 10;
var timer = setInterval(function(){
var current = parseFloat(getComputedStyle(element).left);
if (Math.abs(current - target) <= Math.abs(speed)) {
clearInterval(timer);
element.style.left = target + 'px';
} else {
element.style.left = current + speed + 'px';
}
}, interval);
}
</script>
</body>
</html>
在缓冲动画中,物体的移动速度是动态变化的,刚开始移动速度较快,但是随着移动的距离越来越小,移动的速度越来越慢,让物体的移动更加自然。
缓冲动画的实现过程:
代码实现如下:
function move(element, target, duration){
var start = parseFloat(getComputedStyle(element).left);
var distance = target - start;
var interval = 10;
var speed = distance / duration;
var factor = 0.3;
var timer = setInterval(function(){
var current = parseFloat(getComputedStyle(element).left);
var remain = target - current;
var delta = remain * factor;
if (Math.abs(delta) < 1) {
clearInterval(timer);
element.style.left = target + 'px';
} else {
element.style.left = current + delta + 'px';
}
}, interval);
}
下面是一个缓冲动画的示例,点击开始按钮后,红色的盒子会从左边缓慢移动到右边。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>缓冲动画示例</title>
<style>
#box {
position: absolute;
left: 0;
top: 100px;
width: 50px;
height: 50px;
background: red;
}
</style>
</head>
<body>
<div id="box"></div>
<button onclick="move(document.getElementById('box'), 500, 3000)">开始</button>
<script>
function move(element, target, duration){
var start = parseFloat(getComputedStyle(element).left);
var distance = target - start;
var interval = 10;
var speed = distance / duration;
var factor = 0.3;
var timer = setInterval(function(){
var current = parseFloat(getComputedStyle(element).left);
var remain = target - current;
var delta = remain * factor;
if (Math.abs(delta) < 1) {
clearInterval(timer);
element.style.left = target + 'px';
} else {
element.style.left = current + delta + 'px';
}
}, interval);
}
</script>
</body>
</html>
以上就是Javascript匀速动画和缓冲动画的详细讲解,希望对大家有所帮助。