Professional Documents
Culture Documents
COMPUTER
GRAPHICS
PROGRAMMING
Drawing in Canvas
01
The Basic Rectangle
Shape
The Basic Rectangle Shape
● On Canvas, basic rectangle shapes can be drawn in three
different ways: filling, stroking or clearing.
● Rectangles can also be built using paths.
● Rectangle Canvas functions:
➢ fillRect(x,y,width,height) - Draws a filled rectangle at
position x,y for width and height.
➢ strokeRect(x,y,width,height) - Draws a rectangular outline
at position x,y for width and height. This makes use of the
current strokeStyle, lineWidth, lineJoin, and miterLimit
settings.
The Basic Rectangle Shape
➢ clearRect(x,y,width,height) - Clears the specified area and
makes it fully transparent (using transparent black as the
color) starting at position x,y for width and height.
● Before these functions can be used, the fill or stroke style must
be set up first.
● The most basic way to set these styles is to use a color value
represented by a 24-bit hex string. Here is an example from our
first demonstration:
The Basic Rectangle Shape
● The fill style is simply set to be the RGB color black, while the
stroke style is a classic purple color
02
The Canvas State
The Canvas State
● Paths are a method we can use to draw any shape on the canvas.
A path is simply a list of points, and lines to be drawn between
those points.
● A Canvas context can have only a single “current” path, which is
not stored as part of the current drawing state when the
context.save() method is called.
Starting and Ending a Path
➢ The x and y values define the center of our circle, and the
radius will be the radius of the circle upon which our arc will
be drawn. startAngle and endAngle are in radians, not
degrees. anticlockwise is a true or false value that defines
the direction of the arc.
Arc
● For example, if we want to draw a circle with a center point at
position 100,100 and with a radius of 20, we could use the
following code for the contents of drawScreen():
Arc
● Notice that we have to convert our start angle (0) and our end
angle (360) into radians by multiplying them by (Math.PI/180). By
using 0 as the start angle and 360 as the end, we create a full
circle.
● We can also draw a segment of a circle by not specifying the
entire 0 to 360 start and stop angles. This code for drawScreen()
will create one-quarter of a circle drawn clock‐ wise.
Arc
● If we want to draw everything but the 0–90 angle, as shown in
Figure 2-6, we can employ the anticlockwise argument and set it
to true:
Arc
● context.arcTo()