線上服務(wù)咨詢
Article/文章
記錄成長(zhǎng)點(diǎn)滴 分享您我感悟
如何實(shí)現(xiàn)小程序動(dòng)畫?小程序動(dòng)畫的實(shí)現(xiàn)方法
發(fā)表時(shí)間:2019-05-20 08:50:29
文章來(lái)源:沈陽(yáng)網(wǎng)站建設(shè)
標(biāo)簽:小程序 css javascript
瀏覽次數(shù):0
在普通的網(wǎng)頁(yè)開發(fā)中,動(dòng)畫效果可以通過(guò)css3來(lái)實(shí)現(xiàn)大部分需求,在小程序開發(fā)中同樣可以使用css3
,同時(shí)也可以通過(guò)api
方式來(lái)實(shí)現(xiàn)。
API解讀
小程序中,通過(guò)調(diào)用api
來(lái)創(chuàng)建動(dòng)畫,需要先創(chuàng)建一個(gè)實(shí)例對(duì)象。這個(gè)對(duì)象通過(guò)wx.createAnimation
返回,animation
的一系列屬性都基于這個(gè)實(shí)例對(duì)象。
創(chuàng)建這個(gè)對(duì)象
let animation = wx.createAnimation({ duration: 2000, delay: 0, timingFunction: "linear", });
這個(gè)animation
就是通過(guò)wx.createAnimation
之后返回的實(shí)例。在創(chuàng)建過(guò)程中,可以給這個(gè)實(shí)例添加一些屬性,如以上代碼所示,等同于css3
中animation:$name 2s linear
的寫法。
添加動(dòng)效
實(shí)例創(chuàng)建完成之后,基于該實(shí)例,添加需要的動(dòng)態(tài)效果,動(dòng)態(tài)類型可以查閱文檔得知,以最常見的移動(dòng),旋轉(zhuǎn)為例:
animation.translate($width, 0).rotate($deg);
結(jié)束動(dòng)畫
.step()
表示一組動(dòng)畫的結(jié)束
animation.step();
導(dǎo)出動(dòng)畫
動(dòng)畫效果添加完成了,如何給想要的dom添加動(dòng)效呢。這里需要用到.export()
導(dǎo)出動(dòng)畫隊(duì)列,賦值給某個(gè)dom對(duì)象。
this.setData({ moveOne: animation.export() })
<view animation="{{moveOne}}"></view>
例子
以下將通過(guò)2組動(dòng)畫,來(lái)對(duì)比一下css3
與api
實(shí)現(xiàn)方式的不同。
一、模塊移動(dòng)動(dòng)畫
動(dòng)畫效果:
下圖有兩組動(dòng)畫,分別為api
方式(上)與css3
方式(下)完成的效果,點(diǎn)擊move按鈕,動(dòng)畫匯海。
代碼實(shí)現(xiàn)
以下分別為css3
與api
的核心代碼:
css3:
<!-- wxml --> <view class='border'> <view class='css-block {{isMove && "one"}}'></view> <view class='css-block {{isMove && "two"}}'></view> <view class='css-block {{isMove && "three"}}'></view> <view class=沈陽(yáng)軟件制作'css-block {{isMove && "four"}}'></view> </view>
// scss @mixin movePublic($oldLeft,$oldTop,$left,$top) { from { transform:translate($oldLeft,$oldTop); } to { transform:translate($left,$top); } } @mixin blockStyle($color,$name) { background: $color; animation:$name 2s linear infinite alternate; } .one { @include blockStyle(lightsalmon,onemove); } @keyframes onemove { @include movePublic(50rpx,-25rpx,-150rpx,0rpx); } .two { @include blockStyle(lightblue,twomove); } @keyframes twomove { @include movePublic(0rpx,25rpx,-50rpx,0rpx); } .three { @include blockStyle(lightgray,threemove); } @keyframes threemove { @include movePublic(0rpx,25rpx,50rpx,0rpx); } .four { @include blockStyle(grey,fourmove); } @keyframes fourmove { @include movePublic(-50rpx,-25rpx,150rpx,0rpx); }
// js moveFunction(){ this.setData({ isMove: true }) }
css3
中通過(guò)動(dòng)態(tài)改變class
類名來(lái)達(dá)到動(dòng)畫的效果,如上代碼通過(guò)one
、two
、three
、four
來(lái)分別控制移動(dòng)的距離,通過(guò)sass可以避免代碼過(guò)于冗余的問題。
小程序,css,javascript