addColorStop method

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

HTML Canvas 2D Context, Section 5

Syntax

CanvasGradient.addColorStop(offset, color);

Parameters

offset [in]

Type: number

A floating point value between 0.0 and 1.0 that represents the position between the start and end points in a gradient.

color [in]

Type: string

A CSS color string to display at the position that the offset parameter specifies.

Return value

This method does not return a value.

Standards information

Remarks

You can call the addColorStop method multiple times to change a gradient. If you never call this method for CanvasGradient, the gradient is not visible. You need to create at least one color stop to have a visible gradient.

When you use createLinearGradient, you set a width for your gradient. If your shape is wider than the gradient width, then the extra part will be filled with the last color in gradient. .

Examples

The following code example creates a gradient. In this example, the gradient width is set to canvas width. There are two rectangles that are offset to show how the gradient goes across the whole canvas, and only certain colors are displayed in the rectangles. See the sample in action.


<!DOCTYPE html>
<html>
<head>
  <title>AddColorStop example</title>
    <style type="text/css">
       #MyCanvas {
         border:1px solid black;
       }
    </style>
 
</head>
<body>
  <canvas id="MyCanvas" width="600" height="500">This browser or document mode doesn't support canvas</canvas>

   <script>
 
       var canvas = document.getElementById("MyCanvas");
       if (canvas.getContext) {
         var ctx = canvas.getContext("2d");
         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>

</body>
</html>



See also

CanvasGradient
Reference
createRadialGradient
createLinearGradient

 

 

Show:
© 2014 Microsoft. All rights reserved.