Linear gradient in HTML5

A gradient effect specifies a starting color, an ending color, and an area over which color changes and when the gradient effect defined by a straight line(gradient line) then it will be Linear gradient.
To Draw a linear gradient on HTML5 Canvas, use the createLinearGradient() method as:

var objGradient = ctx.createLinearGradient(x1, y1, x2, y2);

The points (x1,y1) and (x2,y2) will be the points of the gradient line.
We need to add colors to this gradient, for it we use the addColorStop method. The addColorStop method consists a color and a
position between 0 and 1, inclusive, where 0 is the beginning and 1 is the end of the gradient.

objGradient.addColorStop(0, 'black');
objGradient.addColorStop(1, 'white');

linear gradient in html5

The following code snippet is the full code to draw a rectangle with the linear gradient.

  <title>Draw gradient/title>
    <style type="text/css">
        #MyCanvas {border:1px solid black;}
  <script type="text/javascript">
      function drawGradient() {
          var ctx;
          var canvas = document.getElementById("MyCanvas");
          if (canvas.getContext) {
              ctx = canvas.getContext("2d");
              //create gradient
              var objGrad = ctx.createLinearGradient(0, 100, 400, 100);
              objGrad.addColorStop(0, 'gray');
              objGrad.addColorStop(1, 'white');
              //set the fillstyle to gradient
              ctx.fillStyle = objGrad;
              ctx.fillRect(0, 0, 400, 200);
<body onload="drawGradient();">
  <canvas id="MyCanvas" width="400" height="200">
  This browser or document mode doesn't support canvas object</canvas>

See another example:

Post navigation