In this tutorial, we will look at examples of each. In the next four examples, we will draw a rectangle onto the HTML5 Canvas element and show examples for each type of fill.
Solid Color
Filling a shape with a solid color is the easiest method. We can use fillStyle property and fill() method.
Linear Gradient
To create a linear gradient onto the HTML5 Canvas, we can use the createLinearGradient() method. Linear gradients are defined by creating boundaries in the direction of the gradient and filling with color using the addColorStop property. The direction of the linear gradient moves from the starting point to the ending point of the imaginary boundary defined with createLinearGradient() method. In this example, we will use two color stops. Color stops are placed along the boundaries between 0 and 1, where 0 is at the starting point, and 1 is at the ending point.
Radial Gradient
To create a radial gradient with HTML5 Canvas, we can use the createRadialGradient() method. Radial gradients are defined using two imaginary circles – a starting circle and an ending circle. The gradient begins with the start circle and moves towards the ending circle.
Pattern Fill
To create a pattern onto the HTML5 Canvas, we can use the createPattern() method of the canvas context which returns a pattern object, set the fillStyle property to the pattern object, and then fill the shape using fill(). The createPattern() method requires an image object and a repeat option, which can be repeat, repeat-x, repeat-y, or no repeat. Unless otherwise specified, the repeat option is defaulted to repeat.