There are a large number of drawing functions that we can use, belonging to the context object. For example, to draw a red rectangle with blue rim, with its top left corner at (100, 100), width 50 and height 40:
g2.fillStyle = "red";
g2.fillRect (100, 100, 50, 40);
g2.strokeStyle = "blue";
g2.strokeRect (100, 100, 50, 40);
Or to draw a green line consisting of a series of straight segments, build a "path" and then stroke it to draw it with a line width of 4 pixels:
g2.beginPath ();
g2.moveTo (x1, y1);
g2.lineTo (x2, y2);
g2.lineTo (x3, y3);
//g2.closePath();
g2.strokeStyle = "green";
g2.lineWidth = 4;
g2.stroke ();
If the path had included the g2.closePath()
back to the start, forming a closed path, it would then be possible to do g2.fill();
.
The context always keeps hold of one strokeStyle
(line colour), one fillStyle
(solid colour), the lineWidth
and one path.
There is not a fillCircle() or strokeCircle() function. Instead you first need to construct a closed path as an arc going from 0 to 360 degrees (= 2.pi radians):
g2.beginPath ();
g2.arc (centreX, centreY, radius, 0, Math.PI * 2, false);
g2.closePath ();
g2.fillStyle = colour;
g2.fill ();
The first 3 parameters of g2.arc()
are obvious because of their names (it's always a good thing to make names meaningful). The others are: starting angle, finishing angle, and whether going clockwise. Angles are in radians, not degrees (pi radians = 180 degrees).
There are two other new things here. Multiplication is always done with *
because x would be the name of a variable. Math
is a special predefined object that has some constants, such as Math.PI
and also many functions, such as Math.sqrt(x)
(square root) and trigonometrical functions. Search "mdn math" for a full list.