window.requestAnimFrame = (function (callback,time) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimaitonFrame || function (callback) { window.setTimeout(callback, time); }; })();
/* * t: current time(当前时间,小于持续时间,tween返回当前时间目标的状态); * b: beginning value(初始值); * c: change in value(变化量); * d: duration(持续时间)。 */
每一个效果都分三个缓动方式,分别是:javascript
1.java
var t = 0, b = 0, c = 100, d = 10; var step = function () { // value就是当前的位置值 // 例如咱们能够设置DOM.style.left = value + 'px'实现定位 var value = Tween.Linear(t, b, c, d); t++; if (t <= d) { // 继续运动 requestAnimationFrame(step); } else { // 动画结束 } };
2.返回顶部/setIntervalweb
backTop(){ var Tween = { Linear: function(t, b, c, d) { //匀速运动 return c * t / d + b; } } Math.tween = Tween; var t = 0; const b = document.documentElement.scrollTop; const c = 100; const d = 5; const setInt = setInterval(()=>{ t--; //console.log(t) if(document.documentElement.scrollTop == 0){clearInterval(setInt)} //console.log(t); const backTop = Tween.Linear(t,b,c,d); //console.log(backTop); document.documentElement.scrollTop = backTop; },5) },
学趣乐园,backLeft算法
npm install @tweenjs/tween.js
var box = document.createElement('div'); box.style.setProperty('background-color', '#008800'); box.style.setProperty('width', '100px'); box.style.setProperty('height', '100px'); document.body.appendChild(box); // 动画循环 function animate(time) { requestAnimationFrame(animate); TWEEN.update(time); } requestAnimationFrame(animate); var coords = { x: 0, y: 0 }; // 开始位置 var tween = new TWEEN.Tween(coords) // 建立一个更改目标的tween .to({ x: 300, y: 200 }, 1000) // 目的位置,1s .easing(TWEEN.Easing.Quadratic.Out) // 平滑动画 .onUpdate(function() { // 目标更新后调用 // CSS translation box.style.setProperty('transform', 'translate(' + coords.x + 'px, ' + coords.y + 'px)'); }) .start();