提交 38eb4291 编写于 作者: H hdx

ball: 增加 fps

上级 5f76446b
<template> <template>
<view class="page-body"> <view class="page-body">
<canvas id="canvas" class="canvas"></canvas> <canvas id="canvas" class="canvas"></canvas>
<text class="fps">FPS: {{fpsString}}</text>
</view> </view>
</template> </template>
<script setup> <script setup>
let fpsString = ref("-/-ms")
class Ball { class Ball {
private width : number private width : number
private height : number private height : number
...@@ -53,7 +56,9 @@ ...@@ -53,7 +56,9 @@
private ballInlayer = 20 private ballInlayer = 20
private runningFlag : boolean = false private runningFlag : boolean = false
private _animateResult: number = 0 private _animateTaskId: number = 0
private frameCount = 0
private lastTime = 0
constructor(ctx : CanvasRenderingContext2D) { constructor(ctx : CanvasRenderingContext2D) {
this.ctx = ctx this.ctx = ctx
...@@ -96,20 +101,31 @@ ...@@ -96,20 +101,31 @@
if (!this.runningFlag) { if (!this.runningFlag) {
return return
} }
this._animateResult = requestAnimationFrame((_: number) => { this._animateTaskId = requestAnimationFrame((timestamp: number) => {
this.animate() this.animate()
this.updateFPS(timestamp)
}) })
} }
updateFPS(timestamp : number) {
this.frameCount++
if (timestamp - this.lastTime >= 1000) {
const timeOfFrame = (1000 / this.frameCount)
fpsString.value = `${this.frameCount} / ${timeOfFrame.toFixed(3)}ms`
this.frameCount = 0
this.lastTime = timestamp
}
}
start() { start() {
cancelAnimationFrame(this._animateResult) cancelAnimationFrame(this._animateTaskId)
this.runningFlag = true this.runningFlag = true
this.animate() this.animate()
} }
stop() { stop() {
this.runningFlag = false this.runningFlag = false
cancelAnimationFrame(this._animateResult) cancelAnimationFrame(this._animateTaskId)
} }
} }
...@@ -155,4 +171,9 @@ ...@@ -155,4 +171,9 @@
margin: auto; margin: auto;
background-color: #fff; background-color: #fff;
} }
.fps {
margin-left: 15px;
margin-top: 30px;
}
</style> </style>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册