In ordinary web development, animation effects can be achieved through CSS3 most requirements, in small program development can also use CSS3, but also through the API way to achieve.

Directions: small program animatiom animation API

The API reading

Small program, by calling API to create animation, need to create an instance object. This object is returned via wx.createAnimation, and the animation’s properties are based on this instance object.

Create this object

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

This animation is the instance returned by wx.createAnimation. During creation, you can add some properties to the instance, as shown in the code above, which is equivalent to animation:$name 2S Linear in CSS3.

Add the dynamic effect

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

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

The end of the animation,

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

    animation.step();
Copy the code

Export animation

Now that the animation has been added, how do you add animation effects to the DOM you want? Here we use.export() to export the animation queue and assign it to a DOM object.

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

example

Here are two sets of animations to compare how CSS3 and API are implemented.

First, module movement animation

Animation effect:

There are two groups of animation in the picture below, which are the effect completed by API (top) and CSS3 (bottom) respectively. Click the Move button to start the animation.

Code implementation

The following is the core code of CSS3 and API respectively:

CSS 3:
    <! -- 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>
Copy the code
    // 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);
    }
Copy the code
    // js
    moveFunction(){
        this.setData({
            isMove: true})}Copy the code

Css3 dynamically changes the name of the class class to achieve the effect of animation, such as the code by one, two, three, four respectively to control the distance of movement, through sASS can avoid the problem of code redundancy. (For details on how to use Sass in small programs, 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(); // This event triggers the CSS3 module to move
    },

    // Module movement method
    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] represents the array object to be animated
                [ele]: animation.export()
            })
          }.bind(this), 2000)
        }
        moveFunc();
        let interval = setInterval(moveFunc,4000)}Copy the code

As can be seen from the renderings, modules are simply moving between each other, and their motion changes can be written as a common event, which can be moved to different positions by passing values to the event. The parameters w, H, M, and ele represent the horizontal movement distance of divergence, the vertical direction when converging, the horizontal distance, and the object for which animationData needs to be modified.

The animation generated in this way could not be retracted according to the original trajectory, so a timer was set after the event, defining another animation to be executed after 2 seconds. At the same time, the animation can only be executed once. If you need the animation effect of the loop, you should wrap a repeating timer in the outer layer.

Look at the source code, found API way is through JS insert and change the inline style to achieve the animation effect, the following GIF can clearly see the style change.

Print the assigned animationData, which contains the type and parameters of the animation event. Options stores configuration options for this animation, Transition stores configuration options for wx.createAnimation, and transformOrigin is the default configuration, which means that the animation starts at the center of the object. This can also be configured at wx.createAnimation.

Two, music playback animation

The above module movement animation does not involve logical interaction, so we try a new music playing animation, which needs to realize the effect of pause and continue.

Animation effect:

Two groups of different animation effect comparison, respectively API (top) implementation and CSS3 implementation (bottom) :

Code implementation

The following are the cSS3 implementation and API implementation of the core code:

CSS 3:
    <! -- 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>
Copy the code
    // scss
    .musicRotate{
        animation: rotate 3s linear infinite;
    }
    
    @keyframes rotate{
        from{
            transform: rotate(0deg)
        }
        to{
            transform: rotate(359deg)
        }
    }
    
    .musicPaused{
        animation-play-state: paused;
    }
Copy the code
    // js
    playTwo(){
        this.setData({
            playTwo:!this.data.playTwo
        },()=>{
            let back = this.data.backgroundAudioManager;
            if(this.data.playTwo){
                back.play();
            } else{ back.pause(); }})}Copy the code

The playTwo property determines whether to pause and controls the addition and removal of CSS classes. When false, the.MusicPaused class is added and the animation is paused.

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>
Copy the code
    // js
    play(){
        this.setData({
            play:!this.data.play
        },()=>{
            let back = this.data.backgroundAudioManager;
            if (!this.data.play) {
                back.pause();
               // Cross-event clear timer
               clearInterval(this.data.rotateInterval);
            } else {
                back.play();
                // Continue the rotation, this.data. I records the degree of rotation
                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
        );
        // Global timing event
        this.setData({
            rotateInterval: rotateInterval
        })
    }
Copy the code

This is done through the API by removing animationData to control the animation. Suspending the animation also requires clearing the timer. Since clearing the timer needs to operate across events, a global method, rotateInterval, is used.

The API method defines the rotation Angle, but after the rotation Angle will stop, if you need to achieve repeated rotation effect, you need to complete the timer. Therefore, the variable I is defined, and the timer increments by 1 every time, equal to 30° rotation every 1s. The degree in animation.rotate() is dynamically assigned. To continue animation after pausing, you need to rotate from the original Angle, so the variable I needs to be global.

Code changes

As you can see from the figure below, THE API-style rotation is done by accumulating angles, rather than in a loop in CSS3.

contrast

By comparing the two small examples above, cSS3 is a better choice in terms of both convenience and amount of code. The API approach has many limitations:

  1. Animations can only be executed once, and loop effects need to be completed through timers.
  2. A timer must be defined if you cannot return to the original path.
  3. Frequent use of timers can hurt performance.

Above all, it is recommended to complete the animation effect through CSS3.

Spread the word

This article is published in Front of Mint Weekly. Welcome to Watch & Star.

Welcome to the discussion. Give it a thumbs up before we go. ◕ ‿ ◕. ~