CGPL Lecture4
CGPL Lecture4
COMPUTER
GRAPHICS
PROGRAMMING
Introduction to HTML5 Canvas
01
SIMPLE CANVAS
TRANSFORMATION
SIMPLE CANVAS TRANSFORMATION
● Transformations on the canvas refer to the mathematical
adjustment of physical properties of drawn shapes. The two most
commonly used shape transformations are scale and rotate.
● An object on the canvas is said to be at the 0 angle rotation when
it is facing to the left.
● Consequently, if we draw an equilateral box (all four sides are the
same length), it doesn’t have an initial facing side other than one
of the flat sides facing to the left. Let’s draw that box for
reference:
ROTATION AND TRANSLATION
● Now, if we want to rotate the entire canvas 45
degrees, we need to do a couple simple steps. First,
we always set the current Canvas transformation to
the “identity” (or “reset”) matrix:
● What we would like is for the red square to remain in place and
to scale from its center. We do this by translating to the center of
the square before we scale, and by drawing the square around
this center point.
COMBINING SCALE AND ROTATION
TRANSFORMATIONS
● Canvas transformations like scale and rotation can be applied to
an object. The below code display how to combine scale(2,2) and
rotate(angleInRadians) from the previous examples:
03
FILLING OBJECTS WITH
COLORS AND GRADIENTS
SETTING BASIC FILL COLORS
● The Canvas fillStyle property is used to set a basic color for filling
shapes on the canvas. Previous examples used simple color
names for fillStyle. An example is
➢ Setting the fill color with a hex number string - We can also
set the fillStyle color with a hex number in a string:
SETTING BASIC FILL COLORS
➢ Setting the fill color with the rgba() method - The rgba()
method allows us to specify a 32-bit color value with the
final 8 bits representing the alpha value of the fill color:
FILLING SHAPES WITH GRADIENTS
● There are two basic options for creating gradient fills on the
canvas: linear and radial.
● A linear gradient creates a horizontal, vertical, or diagonal fill
pattern; the radial variety creates a fill that “radiates” from a
central point in a circular fashion.
LINEAR GRADIENTS
● Linear gradients come in three basic styles: horizontal, vertical,
and diagonal. We control where colors change in our gradient by
setting color stops at points along the length of the object we
want to fill.
● Below is an example of a horizontal gradient:
LINEAR GRADIENTS
● To create the horizontal gradient, we must first create a
variable (gr) to reference the new gradient. Here’s how
we set it:
● The first color was red set at 0, a green color at .5 (the center),
and another red color at 1. This will fill our shape with a relatively
even red to green to red gradient.
APPLYING A HORIZONTAL GRADIENT TO A COMPLEX SHAPE