Skip to main content
createLinearGradient method

Creates an object that represents a linear gradient to use in a canvas context.

The canvas element, Section 5 Internet Explorer 9

Syntax

var retval = CanvasRenderingContext2D.createLinearGradient(x0, y0, x1, y1);

Parameters

x0 [in]

Type: number

The x-coordinate, in pixels, of the start point of the gradient.

y0 [in]

Type: number

The y-coordinate, in pixels, of the start point of the gradient.

x1 [in]

Type: number

The x-coordinate, in pixels, of the end point of the gradient.

y1 [in]

Type: number

The y-coordinate, in pixels, of the end point of the gradient.

Return value

Type: ICanvasGradient

A CanvasGradient object that represents the new linear gradient.

Standards information

Examples

The following code example creates a gradient.

Illustration of the linear gradient object example

<!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

CanvasRenderingContext2D