您好,登錄后才能下訂單哦!
最近小程序中有一個(gè)圖片旋轉(zhuǎn)的需求,最初是想著通過切換多張圖片達(dá)到旋轉(zhuǎn)的效果,后來發(fā)現(xiàn)微信小程序帶有動(dòng)畫api,然后就改由image+Animation來實(shí)現(xiàn)。
首先在wxml中定義image
<image class="bth_image2" mode="aspectFit" animation="{{animation}}" src='../../images/***.png'></image>
注意其中的animation屬性,image就由它來實(shí)現(xiàn)動(dòng)畫。
而{{animation}}我們?cè)趈s的data中定義
data: { animation: '' },
改變animation的值(官網(wǎng)提供角度范圍是-180~180,但是我發(fā)現(xiàn)角度越大會(huì)一直旋轉(zhuǎ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() }) },
相關(guān)代碼
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' }) }, /** * 實(shí)現(xiàn)image旋轉(zhuǎn)動(dòng)畫,每次旋轉(zhuǎn) 120*n度 */ rotateAni: function (n) { _animation.rotate(120 * (n)).step() this.setData({ animation: _animation.export() }) }, /** * 開始旋轉(zhuǎn) */ startAnimationInterval: function () { var that = this; that.rotateAni(++_loadImagePathIndex); // 進(jìn)行一次旋轉(zhuǎn) _animationIntervalId = setInterval(function () { that.rotateAni(++_loadImagePathIndex); }, _ANIMATION_TIME); // 沒間隔_ANIMATION_TIME進(jìn)行一次旋轉(zhuǎn) }, /** * 停止旋轉(zhuǎn) */ stopAnimationInterval: function () { if (_animationIntervalId> 0) { clearInterval(_animationIntervalId); _animationIntervalId = 0; } }, }
微信自帶的Animation可以實(shí)現(xiàn)一次動(dòng)畫,然后可以通過setInterval來達(dá)到不斷旋轉(zhuǎn)的目的,在使用時(shí),控制startAnimationInterval和stopAnimationInterval即可。
注意:
這里為什么不直接給_animation.rotate(120 * (n)).step()設(shè)置一個(gè)足夠大的值,原因有兩點(diǎn):
1、我們需要便利的控制開始和停止,
2、animation在小程序進(jìn)入后臺(tái)后,會(huì)持續(xù)運(yùn)行,占用手機(jī)內(nèi)存和cpu,而小程序依賴于微信,在iphone上會(huì)導(dǎo)致微信被終止運(yùn)行
在使用animation時(shí),會(huì)發(fā)現(xiàn)有時(shí)候出現(xiàn)旋轉(zhuǎn)速度很快或者反向旋轉(zhuǎn)再正向旋轉(zhuǎn)的清空,這都是由于rotate的值設(shè)置有問題。
1、rotate的值應(yīng)該是上一次結(jié)束時(shí)的值,
2、如果設(shè)置了全局變量,記得在oncreate時(shí)初始化,不然第二次打開同一頁面會(huì)有問題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。