|
1 | 1 | 'use strict';
|
2 | 2 | /**
|
3 |
| - * We can remove the repetition in the drawing |
4 |
| - * logic by making a function for it. |
| 3 | + * We can _structure_ the properties better, and |
| 4 | + * make the code a little easier to read by |
| 5 | + * constructing objects. |
5 | 6 | *
|
6 |
| - * The `drawRect` function has six parameters: the |
7 |
| - * drawing context and the five rectangle parameters. |
| 7 | + * Our `drawRect` function no longer needs |
| 8 | + * six parameters and the code is easier to read. |
8 | 9 | */
|
9 | 10 |
|
10 |
| -// create five variables |
11 |
| -const rect1x = 100; |
12 |
| -const rect1y = 50; |
13 |
| -const rect1width = 100; |
14 |
| -const rect1height = 200; |
15 |
| -const rect1col = 'crimson'; |
| 11 | +// create an object |
| 12 | +const rect1 = { |
| 13 | + x: 100, |
| 14 | + y: 50, |
| 15 | + width: 100, |
| 16 | + height: 200, |
| 17 | + col: 'crimson', |
| 18 | +}; |
| 19 | + |
| 20 | +// create another object |
| 21 | +const rect2 = { |
| 22 | + x: 300, |
| 23 | + y: 150, |
| 24 | + width: 100, |
| 25 | + height: 200, |
| 26 | + col: 'steelblue', |
| 27 | +}; |
16 | 28 |
|
17 |
| -// create another five variables |
18 |
| -const rect2x = 300; |
19 |
| -const rect2y = 150; |
20 |
| -const rect2width = 100; |
21 |
| -const rect2height = 200; |
22 |
| -const rect2col = 'steelblue'; |
23 | 29 |
|
24 | 30 | // draw a rectangle
|
25 |
| -function drawRect(c, x, y, w, h, col) { |
26 |
| - c.fillStyle = col; |
27 |
| - c.fillRect(x, y, w, h); |
| 31 | +function drawRect(c, r) { |
| 32 | + c.fillStyle = r.col; |
| 33 | + c.fillRect(r.x, r.y, r.width, r.height); |
28 | 34 | }
|
29 | 35 |
|
30 | 36 | // get a handle on the drawing canvas
|
31 | 37 | const ctx = document.querySelector('canvas').getContext('2d');
|
32 | 38 |
|
33 |
| -drawRect(ctx, rect1x, rect1y, rect1width, rect1height, rect1col); |
34 |
| -drawRect(ctx, rect2x, rect2y, rect2width, rect2height, rect2col); |
| 39 | +drawRect(ctx, rect1); |
| 40 | +drawRect(ctx, rect2); |
0 commit comments