Two programs to develop small program animation

Two programs to develop small program animation

In ordinary web page development, animation effects can be used to achieve most of the requirements through css3 css3, and it can also be used in small program development , and it can also be achieved through apimethods.

Guiding the way: small program animation API

API interpretation

In a small program, apito create an animation by calling , you need to create an instance object first. Through the wx.createAnimationreturn of this object , animationa series of properties are based on this instance object.

Create this object

    let animation = wx.createAnimation({
        duration: 2000,
        delay: 0,
        timingFunction: "linear",
    });
 

This animationis wx.createAnimationthe instance returned after passing . In the creation process, may be added to the instance attributes such as shown in the above code, it is equivalent to css3the animation:$name 2s linearwording.

Add animation

After the instance is created, based on the instance, add the required dynamic effects. The dynamic type can be found in the document. Take the most common movement and rotation as an example:

    animation.translate($width, 0).rotate($deg);
 

End animation

.step()Indicates the end of a set of animations

    animation.step();
 

Export animation

The animation effect is added, how to add animation effect to the desired dom. Here you need to .export()export the animation queue and assign it to a dom object.

    this.setData({ moveOne: animation.export() })
 
    <view  animation="{{moveOne}}"></view>
 

example

The following two sets of animations will be used to compare the difference css3with the apiimplementation method.

1. Module moving animation

Animation effect:

There are two sets of animations in the figure below, which are the effects of the apimethod (top) and the css3method (bottom). Click the move button, and the animation will start.

Code

The following are css3the apicore code:

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='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
        })
    }
 

css3By dynamically changing the classclass name to achieve the effect of animation, as the code by one, two, three, fourto control the distance moved by sass avoid redundancy code is too problems. ( sassFor children's shoes tangled in how to use the mini program, please see here: wechat-mina-template )

api:
    moveClick(){
        this.move(-75,-12.5,25,'moveOne');
        this.move(-25,12.5, 0,'moveTwo');
        this.move(25, 12.5,0,'moveThree');
        this.move(75, -12.5,-25,'moveFour');
        this.moveFunction(); // css3 
    },

    // 
    move: function (w,h,m,ele) {
        let self = this;
        let moveFunc = function () {
        let animation = wx.createAnimation({
            duration: 2000,
            delay: 0,
            timingFunction: "linear",
        });
    
        animation.translate(w, 0).step()
        self.setData({ [ele]: animation.export() })
        let timeout = setTimeout(function () {
            animation.translate(m, h).step();
            self.setData({
                //[ele]  
                [ele]: animation.export()
            })
          }.bind(this), 2000)
        }
        moveFunc();
        let interval = setInterval(moveFunc,4000)
    }
 

It can be seen from the effect diagram that the modules are simply moved, and their movement changes can be written as a common event, and they can be moved to different locations by passing values to the event. The parameters w,h,m,elerespectively indicate the distance of the divergence moving in the horizontal direction, the distance in the vertical direction and the horizontal direction when gathering together, and animationDatathe object that needs to be modified .

The animation generated by this method cannot be recovered according to the original trajectory, so a timer is set after the event, and it is defined that another animation is executed after the animation is executed 2s. At the same time, the animation can only be executed once . If a looping animation is required, a repetitive timer should be wrapped in the outer layer.

Looking at the source code, I found that the apiway is to jsinsert and change the inline style to achieve the animation effect. The following animation can clearly see the style change.

Print out the assigned value animationData, animatesstore the type and parameters of the animation event; optionsstore the configuration options of this animation, transitionstore wx.createAnimationthe configuration at the time of invocation, which transformOriginis the default configuration, which means that the animation starts from the center of the object as the starting point , Can also be wx.createAnimationconfigured at the time.

2. Music playback animation

The above module moving animation does not involve logical interaction, so a new music playback animation is tried, which needs to achieve the effect of pause and continue.

Animation effect:

Comparison of two different animation effects, respectively api(top) realization and css3realization (bottom):

Code

The following are the core codes for css3implementation and apiimplementation:

css3:
    <!-- wxml -->
    <view class='music musicTwo musicRotate {{playTwo ? " ": "musicPaused"}} ' bindtap='playTwo'>
        <text class="iconfont has-music" wx:if="{{playTwo}}"></text>
        <text class="iconfont no-music" wx:if="{{!playTwo}}"></text>
    </view>
 
    //scss
    .musicRotate{
        animation: rotate 3s linear infinite;
    }
    
    @keyframes rotate{
        from{
            transform: rotate(0deg)
        }
        to{
            transform: rotate(359deg)
        }
    }
    
    .musicPaused{
        animation-play-state: paused;
    }
 
    //js
    playTwo(){
        this.setData({
            playTwo: !this.data.playTwo
        },()=>{
            let back = this.data.backgroundAudioManager;
            if(this.data.playTwo){
                back.play();
            } else {
                back.pause();
            }
        })
    }
 

Use playTwothis attribute to determine whether to pause, and control cssthe addition and deletion of classes. When is falsethe time to add .musicPaused, animation suspended.

api:
    <!-- wxml -->
    <view class='music' bindtap='play'  animation="{{play && musicRotate}}">
        <text class="iconfont has-music" wx:if="{{play}}"></text>
        <text class="iconfont no-music" wx:if="{{!play}}"></text>
    </view>
 
    //js
    play(){
        this.setData({
            play: !this.data.play
        },()=>{
            let back = this.data.backgroundAudioManager;
            if (!this.data.play) {
                back.pause();
               // 
               clearInterval(this.data.rotateInterval);
            } else {
                back.play();
                // this.data.i 
                this.musicRotate(this.data.i);
            }
        })
    },
    musicRotate(i){
        let self = this;
        let rotateFuc = function(){
            i++;
            self.setData({
                i:i++
            });
            let animation = wx.createAnimation({
                duration: 1000,
                delay: 0,
                timingFunction: "linear",
            });
            animation.rotate(30*(i++)).step()
            self.setData({ musicRotate: animation.export() });
        }
        rotateFuc();
        let rotateInterval = setInterval(
            rotateFuc,1000
        );
        // 
        this.setData({
            rotateInterval: rotateInterval
        })
    }
 

The way to apiachieve this is animationDatato control the animation by removing . At the same time, suspending the animation also needs to clear the timer. Since the clear timer needs to be operated across events, a global method is defined rotateInterval.

apiThe method defines the angle of rotation, but it will stop after rotating to this angle. If you need to achieve the repeated rotation effect, you need to complete it through a timer. Therefore, the variable i is defined, and the timer is incremented by 1 each time it is executed, which is equivalent to rotating 30 every 1s, animation.rotate()and the degree of the center is dynamically assigned. To continue the animation after the pause, you need to continue to rotate from the original angle, so the variable i needs to be a global variable.

Code changes

As can be seen from the figure below, the apiway rotation is completed by continuously accumulating the angle, rather than css3being executed in a loop.

Compared

Through the comparison of the above two small examples, whether it is convenience or amount of code, css3it is relatively better to achieve animation effects through . apiThe method has many limitations:

  1. The animation can only be executed once, and the loop effect needs to be completed by a timer.
  2. It cannot return according to the original track, and a timer must be defined to return.
  3. Frequent use of timers has flaws in performance.

Based on the above, it is recommended css3to complete the animation effect through.

Widely advertising

This article is published in Mint Frontend Weekly , welcome to Watch & Star , please indicate the source for reprinting.

Welcome to discuss, please give me a thumbs up and leave.