Skip to main content
CanvasGradient object

Specifies an object that represents a color gradient fillStyle on a CanvasRenderingContext2D object.

HTML Canvas 2D Context, Section 1 Internet Explorer 9

Members

The CanvasGradient object has these types of members:

Methods

The CanvasGradient object has these methods.

MethodDescription
addColorStop

Adds the specified colors and the position in a CanvasGradient object.

 

Standards information

Remarks

You can create a linear or radial CanvasGradient object by using the createLinearGradient or createRadialGradient method. A CanvasGradient object must have at least one color stop or the gradient is not visible.

Examples

The following code example creates a gradient.


<head>
    <title>Canvas gradient test</title>
  <script type="text/javascript">

      
      function draw() {
              var canvas = document.getElementById("MyCanvas");
          if (canvas.getContext) {  // check for support
              var ctx = canvas.getContext("2d"); 

              //create a gradient object from the canvas context
              gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);

              // Add the colors with fixed stops at 1/4 of the width.
              gradient.addColorStop("0", "magenta");
              gradient.addColorStop(".25", "blue");
              gradient.addColorStop(".50", "green");
              gradient.addColorStop(".75", "yellow");
              gradient.addColorStop("1.0", "red");

              // Use the gradient.
              ctx.fillStyle = gradient;
              ctx.fillRect(0, 0, 300, 250);
              ctx.fillRect(250, 300, 600, 500);
          }
      }        
  </script>
</head>
<body  onload = "draw();">
  <canvas id="MyCanvas" width="600" height="500"> This browser or document mode doesn't support canvas</canvas>
</body>
</html>

See also

Reference
createRadialGradient
createLinearGradient

 

 

Send comments about this topic to Microsoft

Build date: 11/28/2012