animation-frame.uvue 1.8 KB
Newer Older
1 2 3 4 5
<template>
  <view class="page">
    <page-head :title="title"></page-head>
    <button @click="startRequestAnimationFrame">requestAnimationFrame</button>
    <button @click="stopRequestAnimationFrame">cancelAnimationFrame</button>
H
hdx 已提交
6
    <text class="frame-count">FPS: {{fps}} / {{formatFPSTime}}</text>
7
    <text class="frame-count">FrameCount: {{testFrameCount}}</text>
H
hdx 已提交
8
    <text class="tips">提示: 在当前测试例子中,每增加一次调用 requestAnimationFrame 帧率翻倍,cancelAnimationFrame 后恢复</text>
9 10 11 12 13 14 15
  </view>
</template>

<script>
  export default {
    data() {
      return {
H
hdx 已提交
16
        title: 'AnimationFrame',
17
        taskId: 0,
H
hdx 已提交
18 19
        fps: 0,
        formatFPSTime: '0ms',
20 21
        lastTime: 0,
        frameCount: 0,
22 23 24 25 26 27 28 29 30 31
        testFrameCount: 0
      }
    },
    onUnload() {
      if (this.taskId > 0) {
        this.stopRequestAnimationFrame()
      }
    },
    methods: {
      startRequestAnimationFrame() {
H
hdx 已提交
32
        this.taskId = requestAnimationFrame((timestamp : number) => {
33
          this.frameCount++
H
hdx 已提交
34 35
          if (timestamp - this.lastTime >= 1000) {
            this.formatFPSTime = (1000 / this.frameCount).toFixed(3) + 'ms'
36 37 38
            this.fps = this.frameCount
            this.frameCount = 0
            this.lastTime = timestamp
H
hdx 已提交
39 40 41
          }

          this.testFrameCount++
42 43 44
          this.startRequestAnimationFrame()
        })
      },
45 46
      stopRequestAnimationFrame() {
        this.fps = 0
H
hdx 已提交
47
        this.formatFPSTime = '0ms'
48 49
        this.lastTime = 0
        this.frameCount = 0
50
        cancelAnimationFrame(this.taskId)
51 52 53 54 55 56 57 58 59 60 61 62
      }
    }
  }
</script>

<style>
  .page {
    padding: 15px;
  }

  .frame-count {
    margin-top: 15px;
63 64 65 66 67 68
  }

  .tips {
    font-size: 12px;
    margin-top: 30px;
    opacity: 0.7;
69 70
  }
</style>