A canvas element may be used to express a gradient effect of a color filled object.

There two possible kinds of gradient effects, these are:

  • linear and
  • radial

Following methods will define the type of a gradient we want to use, as well as the position where to add a color stop:

  • createLinearGradient(x0, y0, x1, y1) - this method creates a linear gradient
  • createRadialGradient(x0, y0, r0, x1, y1, r1) - this method creates a radial gradient
  • addColorStop(<position>, <color>) - this method indicates a color to be added to existing gradient; we are allowed to add as many colors as we want, and you can also specify where along the gradient pattern the color will appear.

Each color stop of the addColorStop() method has two parameters: position and color. The position is a 0-1 value indicating where on the gradient line the color should be positioned. 0 is the beginning, 1 is the end, and intermediate values are in the middle.

Linear gradients

The createLinearGradient() method is used to create a linear gradient and it expects four parameters. These parameters define a line (x1, y1, x2, y2) of the color. The colors will be perpendicular to this line, so if you want horizontal color bands, draw a vertical line. If you want vertical color bands, draw a horizontal line.

Radial gradients

The createRadialGradient() method is used to create a radial gradient. Radial gradients may be defined with two circles; the start of a gradient is defined by the first circle, while the end of a gradient by the second circle. The addColorStop or more between them may be added as well. Following properties are associated with the createRadialGradient method:

  • beginX - the X position of the starting point which is often in the center of your shape
  • beginY - along with beginX, this determines the beginning position of your gradient
  • beginRadius - radius of the center circle; usually is zero, but may be made larger to emphasize the center color
  • endX - describes the X position of the ending circle and is typically same as beginX
  • endY - along with endX it defines the position of the ending circle; if the beginning and ending circles have the same positions, we get a circular gradient; change the end position will make the gradient stretch in a particular direction
  • endRadius - ending radius defines where the last color gradient will be placed; smaller values lead to a tightly grouped gradient, while larger ones spread the gradient along a larger area

Example

Example of using linear and radial gradient methods:

 

›› go to examples ››