首先展示一下效果,狠狠點擊 https://zhangkunusergit.github.io/vue-component/dist/jitter.html
代碼github : https://github.com/zhangKunUserGit/vue-component
先說一下用法:
<jitter :start.sync="抖動控制器" :range="{ 包含x,y, z }" :shift-percent="0.1"> 這里是你要抖動的元素</jitter>思路:
1.抖動就是擺動,現實中的鐘擺可以很形象。
2.當擺動到臨界點后,就會向相反的方向擺動。
3.在沒有動力時,擺動會慢慢停止。
初始化抖動:
/** * 初始化抖動 */initJitter() { // 把start變成false, 方便下次點擊 this.$emit('update:start', false); // 清除上次動畫 this.clearAnimate(); // 設置currentRange, 填充this.range 中沒有的項 this.currentRange = Object.assign({}, { x: 0, y: 0, z: 0 }, this.range); // 獲取需要操作的的項 和 每次需要擺動的量 const { position, shiftNumber } = this.getPositionAndShiftNumber(); this.position = position; this.shiftNumber = shiftNumber; // 初始 move 起始點是0 this.move = { x: 0, y: 0, z: 0 }; // 初始時 是順時針 this.isClockwise = true; // 執行動畫 this.timer = window.requestAnimationFrame(this.continueJitter);},這里準備動畫開始前的工作。
執行動畫:
// 持續抖動continueJitter() { this.refreshMove(this.isClockwise ? -1 : 1); // 絕對值 const absMove = this.getAbsMove(); const currentRange = this.currentRange; let changeDirection = false; for (let i = 0, l = this.position.length, p; i < l; i += 1) { p = this.position[i]; // 判斷是否到達臨界值,到達后 應該反方向執行動畫 if (currentRange[p] <= absMove[p]) { // 等比例縮減 this.currentRange[p] -= this.shiftNumber[p]; // 判斷如果已經無力再擺動,就讓擺動停止, 只要有一個值達到了0,所有都會達到 if (this.currentRange[p] <= 0) { // 停止在起始點上 this.jitterView({ x: 0, y: 0, z: 0 }); // 清除動畫 this.clearAnimate(); return; } // 更新move為臨界點 this.move[p] = this.isClockwise ? -this.currentRange[p] : this.currentRange[p]; // 改變擺動方向 changeDirection = true; } } if (changeDirection) { // 擺動方向取反 this.isClockwise = !this.isClockwise; } // 更新元素位置 this.jitterView(this.move); // 繼續執行動畫 this.timer = window.requestAnimationFrame(this.continueJitter);},執行動畫,當判斷已經無力擺動后,讓元素回歸到原來的位置,并清除動畫。
修改元素位置:
/** * 修改元素位置 * @param x * @param y * @param z */jitterView({ x = 0, y = 0, z = 0 }) { this.$el.style.transform = `translate3d(${x}px, ${y}px, ${z}px)`;},這里需要判斷需要 Z 軸擺動嗎? 當需要時,必須給當前元素的父級添加 perspective, 從而修改子級透視效果
|
新聞熱點
疑難解答
圖片精選