From 5f76446bc90d7875385e16955af53b6146374dd2 Mon Sep 17 00:00:00 2001 From: hdx Date: Fri, 9 Aug 2024 15:04:27 +0800 Subject: [PATCH] =?UTF-8?q?canvas:=20=E5=A2=9E=E5=8A=A0=20AnimationFrame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/component/canvas/canvas.uvue | 43 +++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/pages/component/canvas/canvas.uvue b/pages/component/canvas/canvas.uvue index 68d27c69..f791c078 100644 --- a/pages/component/canvas/canvas.uvue +++ b/pages/component/canvas/canvas.uvue @@ -37,7 +37,9 @@ {{dataBase64.slice(0,22)}}... - + + + CanvasContext API 演示 @@ -65,14 +67,18 @@ renderingContext: null as CanvasRenderingContext2D | null, canvasWidth: 0, canvasHeight: 0, - dataBase64: '', + dataBase64: '', + taskId: 0, + lastTime: 0, + frameCount: 0, // 仅测试 testCanvasContext: false, testToBlobResult: false, testToDataURLResult: false, testCreateCanvasContextAsyncSuccess: false, testCreateImage: false, - testCreatePath2D: false + testCreatePath2D: false, + testFrameCount: 0 } }, onReady() { @@ -88,7 +94,7 @@ hidpi(this.canvas!); this.canvasWidth = this.canvas!.width; - this.canvasHeight = this.canvas!.height; + this.canvasHeight = this.canvas!.height; // #ifdef WEB context.toBlob((blob : Blob) => { @@ -107,6 +113,11 @@ // this.canvas = canvas; // this.canvasWidth = canvas.width; // this.canvasHeight = canvas.height; + }, + onUnload() { + if (this.taskId > 0) { + this.stopAnimationFrame() + } }, methods: { // #ifdef WEB @@ -148,6 +159,30 @@ path2D.bezierCurveTo(x2, y2, x3, y3, x4, y4); } context.stroke(path2D); + }, + startAnimationFrame() { + if (this.taskId > 0) { + this.stopAnimationFrame() + } + this.taskId = this.canvasContext!.requestAnimationFrame((timestamp : number) => { + this.testFrameCount++ + this.updateFPS(timestamp) + this.startAnimationFrame() + }) + }, + stopAnimationFrame() { + this.canvasContext!.cancelAnimationFrame(this.taskId) + this.taskId = 0 + }, + updateFPS(timestamp : number) { + this.frameCount++ + if (timestamp - this.lastTime >= 1000) { + const timeOfFrame = (1000 / this.frameCount) + this.renderingContext!.clearRect(0, 0, this.canvasWidth, this.canvasHeight) + this.renderingContext!.fillText(`${this.frameCount} / ${timeOfFrame.toFixed(3)}ms`, 10, 18) + this.frameCount = 0 + this.lastTime = timestamp + } } } } -- GitLab