cancel-animation-frame.uvue 1.5 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>
6 7 8
    <text class="frame-count">FPS: {{fps}}</text>
    <text class="frame-count">FrameCount: {{testFrameCount}}</text>
    <text class="tips">提示: 在当前测试例子中,调用一次 requestAnimationFrame 帧率翻倍,cancelAnimationFrame 后恢复</text>
9 10 11 12 13 14 15 16 17
  </view>
</template>

<script>
  export default {
    data() {
      return {
        title: 'cancelAnimationFrame',
        taskId: 0,
18 19 20
        lastTime: 0,
        frameCount: 0,
        fps: 0,
21 22 23 24 25 26 27 28 29 30
        testFrameCount: 0
      }
    },
    onUnload() {
      if (this.taskId > 0) {
        this.stopRequestAnimationFrame()
      }
    },
    methods: {
      startRequestAnimationFrame() {
31 32 33 34 35 36 37 38
        this.taskId = requestAnimationFrame((timestamp : number) => {
          this.testFrameCount++
          this.frameCount++
          if (timestamp - this.lastTime >= 1000) {
            this.fps = this.frameCount
            this.frameCount = 0
            this.lastTime = timestamp
          }
39 40 41 42
          this.startRequestAnimationFrame()
        })
      },
      stopRequestAnimationFrame() {
43
        cancelAnimationFrame(this.taskId)
44 45 46 47 48 49 50 51 52 53 54 55
      }
    }
  }
</script>

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

  .frame-count {
    margin-top: 15px;
56 57 58 59 60 61
  }

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