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>
DCloud-WZF's avatar
DCloud-WZF 已提交
6 7
    <text class="frame-count">FPS: {{FPSString}}</text>
    <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',
DCloud-WZF's avatar
DCloud-WZF 已提交
17
        taskId: 0,
H
hdx 已提交
18
        FPSString: '- / -ms',
19 20
        lastTime: 0,
        frameCount: 0,
21 22 23 24 25 26 27 28 29 30
        testFrameCount: 0
      }
    },
    onUnload() {
      if (this.taskId > 0) {
        this.stopRequestAnimationFrame()
      }
    },
    methods: {
      startRequestAnimationFrame() {
H
hdx 已提交
31
        this.taskId = requestAnimationFrame((timestamp : number) => {
DCloud-WZF's avatar
DCloud-WZF 已提交
32
          this.updateFPS(timestamp)
H
hdx 已提交
33
          this.testFrameCount++
34 35 36
          this.startRequestAnimationFrame()
        })
      },
H
hdx 已提交
37
      stopRequestAnimationFrame() {
DCloud-WZF's avatar
DCloud-WZF 已提交
38 39 40
        cancelAnimationFrame(this.taskId)
        this.lastTime = 0
        this.frameCount = 0
H
hdx 已提交
41
        this.FPSString = '- / -ms'
DCloud-WZF's avatar
DCloud-WZF 已提交
42 43 44 45 46 47 48 49 50
      },
      updateFPS(timestamp : number) {
        this.frameCount++
        if (timestamp - this.lastTime >= 1000) {
          const timeOfFrame = (1000 / this.frameCount)
          this.FPSString = `${this.frameCount} / ${timeOfFrame.toFixed(3)}ms`
          this.frameCount = 0
          this.lastTime = timestamp
        }
51 52 53 54 55 56 57 58 59 60 61 62 63
      }
    }
  }
</script>

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

  .frame-count {
    margin-top: 15px;
  }
DCloud-WZF's avatar
DCloud-WZF 已提交
64 65 66 67 68

  .tips {
    font-size: 12px;
    margin-top: 30px;
    opacity: 0.7;
69
  }
DCloud-WZF's avatar
DCloud-WZF 已提交
70
</style>