animation-frame.uvue 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <template>
  2. <view class="page">
  3. <page-head :title="title"></page-head>
  4. <button @click="startRequestAnimationFrame">requestAnimationFrame</button>
  5. <button @click="stopRequestAnimationFrame">cancelAnimationFrame</button>
  6. <text class="frame-count">FPS: {{FPSString}}</text>
  7. <text class="frame-count">FrameCount: {{testFrameCount}}</text>
  8. <text class="tips">提示: 在当前测试例子中,每增加一次调用 requestAnimationFrame 帧率翻倍,cancelAnimationFrame 后恢复</text>
  9. </view>
  10. </template>
  11. <script>
  12. export default {
  13. data() {
  14. return {
  15. title: 'AnimationFrame',
  16. taskId: 0,
  17. FPSString: '- / -ms',
  18. lastTime: 0,
  19. frameCount: 0,
  20. testFrameCount: 0
  21. }
  22. },
  23. onUnload() {
  24. if (this.taskId > 0) {
  25. this.stopRequestAnimationFrame()
  26. }
  27. },
  28. methods: {
  29. startRequestAnimationFrame() {
  30. this.taskId = requestAnimationFrame((timestamp : number) => {
  31. this.updateFPS(timestamp)
  32. this.testFrameCount++
  33. this.startRequestAnimationFrame()
  34. })
  35. },
  36. stopRequestAnimationFrame() {
  37. cancelAnimationFrame(this.taskId)
  38. this.lastTime = 0
  39. this.frameCount = 0
  40. this.FPSString = '- / -ms'
  41. },
  42. updateFPS(timestamp : number) {
  43. this.frameCount++
  44. if (timestamp - this.lastTime >= 1000) {
  45. const timeOfFrame = (1000 / this.frameCount)
  46. this.FPSString = `${this.frameCount} / ${timeOfFrame.toFixed(3)}ms`
  47. this.frameCount = 0
  48. this.lastTime = timestamp
  49. }
  50. }
  51. }
  52. }
  53. </script>
  54. <style>
  55. .page {
  56. padding: 15px;
  57. }
  58. .frame-count {
  59. margin-top: 15px;
  60. }
  61. .tips {
  62. font-size: 12px;
  63. margin-top: 30px;
  64. opacity: 0.7;
  65. }
  66. </style>