1+ import { memorizeFn } from './memorizeFn'
2+ import { idleCallbackWrapper } from './idleCallbackWrapper'
13export 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