微信小程序 Animation實現(xiàn)圖片旋轉動畫示例
最近小程序中有一個圖片旋轉的需求,最初是想著通過切換多張圖片達到旋轉的效果,后來發(fā)現(xiàn)微信小程序帶有動畫api,然后就改由image+Animation來實現(xiàn)。
首先在wxml中定義image
<image class="bth_image2" mode="aspectFit" animation="{{animation}}" src='../../images/***.png'></image>
注意其中的animation屬性,image就由它來實現(xiàn)動畫。
而{{animation}}我們在js的data中定義
data: { animation: '' },
改變animation的值(官網(wǎng)提供角度范圍是-180~180,但是我發(fā)現(xiàn)角度越大會一直旋轉)
onShow: function() { console.log('index---------onShow()') this.animation = wx.createAnimation({ duration: 1400, timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" delay: 0, transformOrigin: '50% 50% 0', success: function(res) { console.log("res") } }) }, rotateAni: function (n) { console.log("rotate=="+n) this.animation.rotate(180*(n)).step() this.setData({ animation: this.animation.export() }) },
相關代碼
var _animation; var _animationIndex const _ANIMATION_TIME = 500; pages { ... onShow: function () { _animation = wx.createAnimation({ duration: _ANIMATION_TIME, timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" delay: 0, transformOrigin: '50% 50% 0' }) }, /** * 實現(xiàn)image旋轉動畫,每次旋轉 120*n度 */ rotateAni: function (n) { _animation.rotate(120 * (n)).step() this.setData({ animation: _animation.export() }) }, /** * 開始旋轉 */ startAnimationInterval: function () { var that = this; that.rotateAni(++_loadImagePathIndex); // 進行一次旋轉 _animationIntervalId = setInterval(function () { that.rotateAni(++_loadImagePathIndex); }, _ANIMATION_TIME); // 沒間隔_ANIMATION_TIME進行一次旋轉 }, /** * 停止旋轉 */ stopAnimationInterval: function () { if (_animationIntervalId> 0) { clearInterval(_animationIntervalId); _animationIntervalId = 0; } }, }
微信自帶的Animation可以實現(xiàn)一次動畫,然后可以通過setInterval來達到不斷旋轉的目的,在使用時,控制startAnimationInterval和stopAnimationInterval即可。
注意:
這里為什么不直接給_animation.rotate(120 * (n)).step()設置一個足夠大的值,原因有兩點:
1、我們需要便利的控制開始和停止,
2、animation在小程序進入后臺后,會持續(xù)運行,占用手機內(nèi)存和cpu,而小程序依賴于微信,在iphone上會導致微信被終止運行
在使用animation時,會發(fā)現(xiàn)有時候出現(xiàn)旋轉速度很快或者反向旋轉再正向旋轉的清空,這都是由于rotate的值設置有問題。
1、rotate的值應該是上一次結束時的值,
2、如果設置了全局變量,記得在oncreate時初始化,不然第二次打開同一頁面會有問題。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Extjs顯示從數(shù)據(jù)庫取出時間轉換JSON后的出現(xiàn)問題
后臺從數(shù)據(jù)庫取出時間,JSON格式化后再傳到gridpanel,這時時間變成了:/Date(32331121223)/這樣的格式,本文將詳細介紹解決Extjs顯示從數(shù)據(jù)庫取出時間轉換JSON后的出現(xiàn)問題2012-11-11Javascript 正則表達式校驗數(shù)字的簡單實例
下面小編就為大家?guī)硪黄狫avascript 正則表達式校驗數(shù)字的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11js實現(xiàn)數(shù)據(jù)雙向綁定(訪問器監(jiān)聽)
這篇文章主要為大家詳細介紹了采用訪問器監(jiān)聽的方式實現(xiàn)簡單數(shù)據(jù)雙向綁定,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09