Search within TutorialsPark

HTML5 Canvas Gradients


Use canvas methods to draw gradients, both linear and Radial.


The attributes fillStyle and strokeStyle define how the regions and lines are to be filled. But you can have only opaque or translucent colors.

By using CanvasPattern or CanvasGradient objects we can have a linear or radial color gradient.


Linear Gradient: createLinearGradient(x0,y0,x1,y1)

4 Steps to draw a linear gradient.

1.Create a canvas gradient drawing object using method createLinearGradient(x0,y0,x1,y2). Here parameters denote starting and endpoints of the imaginary line along which a gradient is to be created. Eg: context.createlinearGradient(0,20,400,600)

2.Save this drawing object in a variable.

3.Use method addColorStop(offset,color) to define the offset and color of the gradient. Here offset 0.0 denotes color at the (x0,y0) and offset 1.0 denotes the color at (x1,y1) .

4.Finally,assign the variable to fillStyle attribute, its Done!.

Example:Linear Gradient.

Give it a TRY! »


Linear Gradient with multiple colors.

1.In the previous example we had gradient with only two colors,but we can also have multiple color gradients by having different color at different offset points

Eg:linear.addColorStop(0.5,'#fa4b2a');

Example:Linear gradients with multiple colors.

Give it a TRY! »


Radial Gradients: createRadialGradient(x0, y0, r0, x1, y1, r1).

1.In a linear Gradient the offset varies from one point to another.But in a Radial gradient the offset varies from one imaginary circle(smaller) to another(larger).

2.To create a Radial Gradient we use the method createRadialGradient(x0, y0, r0, x1, y1, r1)

Here x0, y0, r0 denote the centre(x0, y0) of the start circle and its radius(r0) respectively.

Similarly x1, y1, r1 denote the centre and radius of finish circle in the radial Gradient respectively.

3.Use addColorStop(offset,color) method to define color at different offset points.

Example:Canvas Radial Gradient.

Give it a TRY! »


Using Canvas to create patterns: createPattern()

1.Small images can be used to tile over a large area, using method createPattern.

2.To create a tile pattern, pass a HTMLImageElement as the first parameter to the method createPattern(Image_variable, Repeat_Pattern). The second parameter "Repeat_Pattern" value can assume 4 values:

repeat:Image is tiled both vertically and horizontally.

repeat-x:Image is tiled(i.e repeated) horizontally.

repeat-y:Image is tiled(i.e repeated) vertically.

no-repeat:Image is not repeated at all.

Example: Pattern using createPattern()

Give it a TRY! »


Using canvas gradients on smaller shapes.

1.In previous example we created gradients on a rectangle of the size of the entire canvas.Now we use gradient on smaller rectangles.

Example: 2D drawing Context

Give it a TRY! »




Related Examples

Related Tags