When drawing onto the HTML5 Canvas, it is fairly common to fill the objects that are rendered with color or patterns. When filling the canvas lines or shapes with color, we can either apply a solid color, linear-gradient, radial-gradient, or a pattern.
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.
context.fillStyle = ‘#FFAA00’; context.fill();
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.
var gradient = context.createLinearGradient(startX, startY, endX, endY); gradient.addColorStop(offset, color);
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.
var gradient = context.createRadialGradient(startX, startY, startRadius, endX, endY, endRadius); gradient.addColorStop(offset, color);
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.
var pattern = context.createPattern(imageObj, repeatOption); context.fillStyle = pattern; context.fill();