Skip to content

Commit cc3d420

Browse files
author
Simon he
committed
⚡️ perf: use memo and splice for rendering
1 parent 2d15e35 commit cc3d420

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

src/DotImageCanvas.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { memorizeFn } from "./memorizeFn"
2-
import { idleCallbackWrapper } from "./idleCallbackWrapper"
1+
import { memorizeFn } from './memorizeFn'
2+
import { idleCallbackWrapper } from './idleCallbackWrapper'
33

44
export class DotImageCanvas {
55
canvas: HTMLCanvasElement = document.createElement('canvas')

src/DotTextCanvas.ts

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { memorizeFn } from './memorizeFn'
2+
import { idleCallbackWrapper } from './idleCallbackWrapper'
13
export class DotTextCanvas {
24
canvas: HTMLCanvasElement = document.createElement('canvas')
35
ctx: CanvasRenderingContext2D = this.canvas.getContext('2d')!
@@ -7,6 +9,7 @@ export class DotTextCanvas {
79
color: string
810
fontWeight: number
911
textPointSet: Array<number[]> = []
12+
status = 'pending'
1013
constructor(text: string, fontSize: number, color: string, fontWeight: number) {
1114
this.originText = text
1215
this.fontSize = fontSize
@@ -62,24 +65,32 @@ export class DotTextCanvas {
6265
const h = this.textPointSet.length
6366
const w = this.textPointSet[0].length
6467
const oneTempLength = this.fontSize / h
68+
const tasks: Function[] = []
69+
const getPoint = memorizeFn((i: number) => oneTempLength * (i + 0.5))
70+
const size = oneTempLength * this.fontWeight / h
6571
this.canvas.height = this.fontSize
6672
this.canvas.width = this.fontSize * this.originText.length
73+
6774
for (let i = 0; i < h; i++) {
68-
for (let j = 0; j < w; j++) {
69-
if (this.textPointSet[i][j]) {
70-
this.ctx.beginPath()
71-
this.ctx.arc(oneTempLength * (j + 0.5), oneTempLength * (i + 0.5), oneTempLength * this.fontWeight / h, 0, Math.PI * 2)
72-
this.ctx.fillStyle = this.color
73-
this.ctx.fill()
75+
tasks.push(() => {
76+
for (let j = 0; j < w; j++) {
77+
if (this.textPointSet[i][j]) {
78+
this.ctx.beginPath()
79+
this.ctx.arc(getPoint(j), getPoint(i), size, 0, Math.PI * 2)
80+
this.ctx.fillStyle = this.color
81+
this.ctx.fill()
82+
}
7483
}
75-
}
84+
})
7685
}
86+
idleCallbackWrapper(tasks, 1000, () => this.status = 'success')
7787
}
7888

7989
repaint(this: any, text: string, fontSize: number, color: string, fontWeight: number): DotTextCanvas {
90+
this.status = 'pending'
8091
// 如果text相同
8192
if (this.originText !== text)
82-
return Object.assign(this, new DotTextCanvas(text, fontSize, color, fontWeight))
93+
return new DotTextCanvas(text, fontSize, color, fontWeight)
8394

8495
this.fontSize = fontSize
8596
this.color = color

0 commit comments

Comments
 (0)