Front-end animation display scheme

In the development process, we usually need some animation effects to make the page more refined. We usually use CSS animation, SVG and so on to achieve these effects, but for some complicated effects, it is not suitable. Our business uses UniAPP, so we need cross-terminal. To solve these problems, we can use the following solutions.

A: Gif/WebP

The advantage is that it can be used as a picture, but the disadvantage is that it takes up large volume and high playback resource, and the content cannot be dynamic

Two: SVGA (recommended)

In the concrete, a canvas will be generated, so it can play it, insert text and other operations.

2.1 download

Liverpoolfc.tv: svga. IO /

Npm:www.npmjs.com/package/svg…

Small program solutions: github.com/yyued/SVGAP…

npm i svgaplayerweb
Copy the code

2.2 the use of

We need to be compatible with H5 and applets, there will be compatibility writing below

Start a resource server and setsvgaFiles are placed on the server:

cd resource
serve . --cros
Copy the code

Business Code:

<template>
    <! -- #ifdef H5 -->
    <div ref="demoCanvas" id="demoCanvas"></div>
    <! -- #endif -->
    <! -- #ifdef MP-WEIXIN -->
    <canvas type="2d" style="width: 300px; height:300px; background-color: black" 			       id="myCanvas"></canvas>
    <! -- #endif -->
</template>

<script>
// #ifdef H5
import SVGA from 'svgaplayerweb'
// #endif

// #ifdef MP-WEIXIN
import SVGA from '.. /.. /.. /static/svga.min.js'
const parser = new SVGA.Parser() New Parser will report requestAnimationFrame error if there is no prior notification
// #endif

export default {
    onLoad() {
        // #ifdef H5
        var player = new SVGA.Player('#demoCanvas')
        var parser = new SVGA.Parser('#demoCanvas')
        parser.load('http://localhost:5000/test.svga'.function(videoItem) {
          player.setVideoItem(videoItem);
          player.startAnimation();
          player.setText('123'.'img_12') // You can replace the corresponding content with the key(layer) provided by uED
        })
        // #endif
        // #ifdef MP-WEIXIN
          let player = new SVGA.Player("#myCanvas")
          parser.load("http://localhost:5000/test.svga".function (videoItem) {
            player.setVideoItem(videoItem);
            player.startAnimation();
          })
        // #endif}}</script>
Copy the code

2.3 check thesvgathekey

Svga. IO /svga-previe…

Drag svGA and select Browse materials to view the keys that can be set

2.4 can be converted intosvg

The website also provides an online address for conversion: www.nangonghan.com/svga/

Iii. Lottie (Recommended)

Lottie is a small, reductive, beginner friendly library. The designer creates the animation and uses the Bodymovin plugin to export the Json file. The front-end directly references the Lottie-Web library, which renders SVG by default and uses JS to manipulate the SVG API. But the front end doesn’t need to care about the animation process at all, the Json file has information about each frame of the animation, and the library executes each frame for us.

3.1 download

Website: reality. The design/Lottie /

Npm:www.npmjs.com/package/lot…

Runtime API library: www.npmjs.com/package/lot…

Small application solution: developers.weixin.qq.com/miniprogram…

Chinese document: www.yuque.com/lottie/docu…

NPM I Lottie -web // Web package NPM I Lottie - API // runtime API library NPM I Lottie - miniProgram // small program packageCopy the code

3.2 the use of

<template>
	<! -- #ifdef H5 -->
    <view id="lottie"></view>
    <! -- #endif -->
    <! -- #ifdef MP-WEIXIN -->
    <canvas id="canvas" type="2d"></canvas>
    <! -- #endif -->
</template>

<script>
// #ifdef H5
import lottie from 'lottie-web'
// #endif
// #ifdef MP-WEIXIN
import lottie from 'lottie-miniprogram'
// #endif
import lottieApi from 'lottie-api'

export default {
    name: 'animateLottie'.props: {
        options: {
          type: Object.default: () = > ({
            loop: false.autoplay: true.// animationData: require('@/static/data.json')})},baseStyle: {
          type: Object.default: () = > ({})
        }
    },
	mounted () {
      let anim
      // #ifdef H5
      anim = lottie.loadAnimation({
        container: document.getElementById('lottie'),
        renderer: 'svg'. this.options }) anim.addEventListener('DOMLoaded'.() = > {
        const api = lottieApi.createAnimationApi(anim)
        this.$emit('ready', {
          anim,
          api
        })
      })
      // #endif

      // #ifdef MP-WEIXIN
      wx.createSelectorQuery().in(this).select('#canvas').node(res= > {
        const canvas = res.node
        const context = canvas.getContext('2d')
        canvas.width = 750
        canvas.height = 1340
        lottie.setup(canvas)
        anim = lottie.loadAnimation({
          rendererSettings: {
            context
          },
        renderer: 'canvas'. this.options }) }).exec()// #endif}}</script>
Copy the code

Call:

animateReady ({anim, api}) {
    const elements = api.getKeyPath("1.88") // In the layer "nm", use commas to look down
    elements.getElements()[0].setText('1.88') // Set the text
    console.log(elements.getElements())
    console.log(anim)
    anim.addEventListener('enterFrame'.(e) = > {
        console.log(e)
    })
  //if (anim.renderer.rendererType === 'canvas') {
    // Image replacement in Canvas mode
  // anim.renderer.elements[0].elements[8].img.src = "' https://gw.alipayobjects.com/mdn/rms_91e1e4/afts/img/A * 2 mfsto - gbDgAAAAAAAAAAABkARQnAQ ';
  //} else {
    // Image replacement in SVG mode, the first two parameters are fixed values
  // anim.renderer.elements[0].elements[8].innerElem.setAttributeNS(
  // 'http://www.w3.org/1999/xlink',
  // 'href',
  // 'https://gw.alipayobjects.com/mdn/rms_91e1e4/afts/img/A*2mfsTo-gbDgAAAAAAAAAAABkARQnAQ'
  / /);
  / /}
    // anim.addEventListener('loopComplete', (e) => {
    // console.log(e)
    // })
}
Copy the code

Note:

  • In this case, we takereadyEvents exposed can be easily bound in correlationapiAnd perform various operations
  • inwebThe end can pass throughapiSet the relevant text, pictures, etc., small program is not possible. evenuedAdding text will cause an error, because the package only supports images, not dynamic text.