@@ -2,10 +2,15 @@ import type { ISignature } from './types'
22import { useEventListener } from './useEventListener'
33import { insertElement } from './insertElement'
44import { removeElement } from './removeElement'
5+ import { useKeyBoard } from './useKeyBoard'
56export class CreateSignatureCanvas implements ISignature {
67 canvas : HTMLCanvasElement = document . createElement ( 'canvas' )
78 ctx : CanvasRenderingContext2D = this . canvas . getContext ( '2d' ) !
89 stop : ( ( ) => void ) [ ] = [ ]
10+ active = false
11+ historyStack : ImageData [ ] = [ ]
12+ resetStack : ImageData [ ] = [ ]
13+
914 constructor ( w = 400 , h = 400 ) {
1015 this . createCanvas ( w , h )
1116 window . onunload = ( ) => this . unmount ( )
@@ -55,9 +60,49 @@ export class CreateSignatureCanvas implements ISignature {
5560
5661 mount ( el : HTMLElement | string ) {
5762 insertElement ( el , this . canvas , null )
63+ this . listen ( )
5864 return this
5965 }
6066
67+ listen ( ) {
68+ useEventListener ( this . canvas , 'mousedown' , ( ) => {
69+ this . active = true
70+ } )
71+ useEventListener ( this . canvas , 'mouseup' , ( ) => {
72+ this . active = false
73+ const { width, height } = this . canvas
74+ const imageData = this . ctx . getImageData ( 0 , 0 , width , height )
75+ this . historyStack . push ( imageData )
76+ } )
77+ useEventListener ( this . canvas , 'mouseout' , ( ) => {
78+ this . active = false
79+ } )
80+ useKeyBoard ( 'Ctrl+z' , ( ) => this . undo ( ) )
81+ useKeyBoard ( 'Ctrl+x' , ( ) => this . redo ( ) )
82+ }
83+
84+ undo ( ) {
85+ if ( this . historyStack . length === 0 )
86+ return
87+ // 清空画布
88+ this . clearCanvas ( )
89+ // 删除当前操作
90+ this . resetStack . push ( this . historyStack . pop ( ) ! )
91+ // 逐个执行绘图动作进行重绘
92+ this . historyStack . forEach ( imageData => this . ctx . putImageData ( imageData , 0 , 0 ) )
93+ }
94+
95+ redo ( ) {
96+ if ( this . resetStack . length === 0 )
97+ return
98+ // 清空画布
99+ this . clearCanvas ( )
100+ // 删除当前操作
101+ this . historyStack . push ( this . resetStack . pop ( ) ! )
102+ // 逐个执行绘图动作进行重绘
103+ this . historyStack . forEach ( imageData => this . ctx . putImageData ( imageData , 0 , 0 ) )
104+ }
105+
61106 unmount ( ) {
62107 removeElement ( this . canvas )
63108 this . stop . forEach ( s => s ( ) )
0 commit comments