HTML Canvas Gradients


Canvas - fillStyle Property

The fillStyle property is used to define a fill-color (or gradient) for the drawing.

Example

Define a red fill-color for a rectangle:

Your browser does not support the canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(20,20,150,100);

Try it Yourself »


Canvas - Gradients

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

There are two different types of gradients:

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

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

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

To use the gradient, set the fillStyle or strokeStyle property to the gradient, and then draw the shape, like a rectangle, text, or a line.

Using createLinearGradient():

Example

Create a linear gradient. Fill rectangle with the gradient:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create gradient
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);

Try it Yourself »

Using createRadialGradient():

Example

Create a radial/circular gradient. Fill rectangle with the gradient:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create gradient
var grd=ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient
ctx.arc(50, 50, 50, 0, 2*Math.PI);
ctx.fillStyle = grd;
ctx.fill();

Try it Yourself »



Color Picker

colorpicker