1
1
import React , { useCallback , useMemo , useRef , useState } from 'react' ;
2
- import { LayoutChangeEvent , StyleSheet , View } from 'react-native' ;
2
+ import { Button , LayoutChangeEvent , StyleSheet , View } from 'react-native' ;
3
3
import {
4
4
Canvas ,
5
5
Group ,
@@ -53,8 +53,7 @@ export const ScratchCard = () => {
53
53
} ) ;
54
54
55
55
const STROKE_WIDTH = useRef < number > ( 40 ) ; // width of the scratch stroke
56
- const totalArea = useRef < number > ( 0 ) ; // Total area of the scratch card
57
- const pathArea = useRef < number > ( 0 ) ; // Total scratched area
56
+ const totalAreaScratched = useRef < number > ( 0 ) ; // Total area scratched on the scratch card
58
57
const [ isScratched , setIsScratched ] = useState ( false ) ; // is canvas scratched enough (> threshold)
59
58
const [ paths , setPaths ] = useState < SkPath [ ] > ( [ ] ) ; // user's scratch data in form of svg path
60
59
@@ -78,25 +77,32 @@ export const ScratchCard = () => {
78
77
paths [ paths . length - 1 ] . toSVGString ( ) ,
79
78
) ;
80
79
81
- pathArea . current +=
82
- pathProperties . getTotalLength ( ) * STROKE_WIDTH . current ;
83
-
84
- const areaScratched = ( pathArea . current / totalArea . current ) * 100 ;
80
+ const pathArea = pathProperties . getTotalLength ( ) * STROKE_WIDTH . current ;
81
+ totalAreaScratched . current += pathArea ;
82
+ const { width, height} = canvasLayoutMeta ;
83
+ const areaScratched =
84
+ ( totalAreaScratched . current / ( width * height ) ) * 100 ;
85
85
86
86
if ( areaScratched > 70 ) {
87
87
setIsScratched ( true ) ;
88
88
// Do other stuff like provide a force feedback to the user (Vibration)
89
89
// Disable the gesture handler to avoid registering more inputs (Saves computation and memory)
90
90
}
91
91
} )
92
- . minDistance ( 1 ) ;
92
+ . minDistance ( 1 )
93
+ . enabled ( ! isScratched ) ;
93
94
94
95
const handleCanvasLayout = useCallback ( ( e : LayoutChangeEvent ) => {
95
96
const { width, height} = e . nativeEvent . layout ;
96
97
setCanvasLayoutMeta ( { width, height} ) ;
97
- totalArea . current = width * height ;
98
98
} , [ ] ) ;
99
99
100
+ const handleReset = ( ) => {
101
+ setIsScratched ( false ) ;
102
+ setPaths ( [ ] ) ;
103
+ totalAreaScratched . current = 0 ;
104
+ } ;
105
+
100
106
const { width, height} = useMemo ( ( ) => canvasLayoutMeta , [ canvasLayoutMeta ] ) ;
101
107
102
108
return (
@@ -137,6 +143,9 @@ export const ScratchCard = () => {
137
143
< Offer width = { width } height = { height } />
138
144
) }
139
145
</ Canvas >
146
+ < View style = { styles . buttonContainer } >
147
+ < Button title = "Reset" onPress = { handleReset } />
148
+ </ View >
140
149
</ View >
141
150
</ GestureDetector >
142
151
) ;
@@ -152,5 +161,8 @@ const styles = StyleSheet.create({
152
161
width : '100%' ,
153
162
height : '100%' ,
154
163
} ,
164
+ buttonContainer : {
165
+ marginTop : 50 ,
166
+ } ,
155
167
} ) ;
156
168
export default ScratchCard ;
0 commit comments