JS运动基础(二) 摩擦运动、缓冲运动

时间:2023-03-08 22:44:16
JS运动基础(二) 摩擦运动、缓冲运动

摩擦运动:

逐渐变慢,最后停止

缓冲运动:

与摩擦力的区别:可以精确的停到指定目标点
距离越远速度越大
速度由距离决定
速度=(目标值-当前值)/缩放系数
Bug:速度取整
值取整:

iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);

JS运动基础(二) 摩擦运动、缓冲运动

 <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width:100px; height: 100px; background: red; position: absolute; left: 0px; top: 30px;}
</style>
<script>
//摩擦,减速 : 在运动过程中,速度越来越慢
//愈接近目标点,速度就越小
window.onload = function() { var oBtn = document.getElementById('btn');
var oDiv = document.getElementById('div1');
var iTimer = null; oBtn.onclick = function() { clearInterval(iTimer);
var iSpeed = 0; iTimer = setInterval(function() { iSpeed = (500 - oDiv.offsetLeft) / 8; iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); console.log( oDiv.offsetLeft + ' : ' + iSpeed ); if (oDiv.offsetLeft == 500) {
clearInterval(iTimer);
} else {
oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
} }, 30); } }
</script>
</head> <body>
<input type="button" value="动起来" id="btn" />
<div id="div1"></div>
</body>
</html>