1
1
'use strict' ;
2
2
/**
3
- * If we want a _second_ rectangle (and simultaneously being
4
- * deliberately naïve) we might just create five additional
5
- * variables and duplicate our drawing code.
3
+ * We can remove the repetition in the drawing
4
+ * logic by making a function for it.
5
+ *
6
+ * The `drawRect` function has six parameters: the
7
+ * drawing context and the five rectangle parameters.
6
8
*/
7
9
8
10
// create five variables
@@ -19,13 +21,14 @@ const rect2width = 100;
19
21
const rect2height = 200 ;
20
22
const rect2col = 'steelblue' ;
21
23
24
+ // draw a rectangle
25
+ function drawRect ( c , x , y , w , h , col ) {
26
+ c . fillStyle = col ;
27
+ c . fillRect ( x , y , w , h ) ;
28
+ }
29
+
22
30
// get a handle on the drawing canvas
23
31
const ctx = document . querySelector ( 'canvas' ) . getContext ( '2d' ) ;
24
32
25
- // draw the rectangle
26
- ctx . fillStyle = rect1col ;
27
- ctx . fillRect ( rect1x , rect1y , rect1width , rect1height ) ;
28
-
29
- // draw it in the new position, with a different colour
30
- ctx . fillStyle = rect2col ;
31
- ctx . fillRect ( rect2x , rect2y , rect2width , rect2height ) ;
33
+ drawRect ( ctx , rect1x , rect1y , rect1width , rect1height , rect1col ) ;
34
+ drawRect ( ctx , rect2x , rect2y , rect2width , rect2height , rect2col ) ;
0 commit comments