11'use strict' ;
22/**
3- * Objects can contain methods.
4- *
5- * Here, we move the `drawRect` function into the class
6- * definition as a `draw` method.
7- *
8- * Methods have access to instance
9- * properties by using `this`.
3+ * We add a `Circle` class to complement our `Rectangle`.
4+ * Circles have `x` and `y` position as well
5+ * as a radius (`r`).
106 */
117
128class Rectangle {
@@ -24,12 +20,32 @@ class Rectangle {
2420 }
2521}
2622
27- // create the two rectangle objects
23+ class Circle {
24+ constructor ( x , y , r , col ) {
25+ this . x = x ;
26+ this . y = y ;
27+ this . r = r ;
28+ this . col = col ;
29+ }
30+
31+ draw ( ctx ) {
32+ ctx . fillStyle = this . col ;
33+ ctx . beginPath ( ) ;
34+ ctx . arc ( this . x , this . y , this . r , 0 , 2 * Math . PI ) ;
35+ ctx . fill ( ) ;
36+ }
37+ }
38+
39+ // create circle and rectangle objects
2840const rect1 = new Rectangle ( 100 , 50 , 100 , 200 , 'crimson' ) ;
2941const rect2 = new Rectangle ( 300 , 150 , 100 , 200 , 'steelblue' ) ;
42+ const circ1 = new Circle ( 150 , 350 , 50 , 'crimson' ) ;
43+ const circ2 = new Circle ( 350 , 450 , 50 , 'steelblue' ) ;
3044
3145// get a handle on the drawing canvas
3246const ctx = document . querySelector ( 'canvas' ) . getContext ( '2d' ) ;
3347
3448rect1 . draw ( ctx ) ;
3549rect2 . draw ( ctx ) ;
50+ circ1 . draw ( ctx ) ;
51+ circ2 . draw ( ctx ) ;
0 commit comments