Gradients in HTML Canvas

Canvas - Gradient

Gradients can be used to fill rectangles, circles, lines, text, and more. Shapes on the canvas are not limited to solid colors.

There are two types of gradients:

  • createLinearGradient(x,y,x1,y1) - Create linear gradient
  • createRadialGradient(x,y,r,x1,y1,r1) - Create radial/circular gradient

Once we have the gradient object, we must add two or more color stops.

The addColorStop() method specifies the color stop and its position along the gradient. The gradient position can be any value between 0 and 1.

To use gradients, set the fillStyle or strokeStyle property to a gradient and then draw shapes (rectangles, text, or lines).

Canvas - Gradients

Using createLinearGradient()

Example

Create linear gradient. Fill rectangle with gradient:

Your browser does not support the HTML5 canvas tag.

JavaScript:

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// Create gradient
const grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// Use gradient to fill
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

Try It Yourself

Using createRadialGradient():

Example

Create radial/circular gradient. Fill rectangle with gradient:

Your browser does not support the HTML5 canvas tag.

JavaScript:

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// Create gradient
const grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// Use gradient to fill
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

Try It Yourself

See Also:

Complete Canvas Reference Manual of CodeW3C.com