HTML Canvas - createLinearGradient() Method



The HTML Canvas createLinearGradient() method of Canvas 2D API of the CanvasRenderingContext2D interface is used to create a gradient along the given co-ordinates.

Syntax

Following is the syntax of HTML Canvas createLinearGradient() method −

CanvasRenderingContext2D.createLinearGradient(x, y, x1, y1); 

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1

x

The x co-ordinate of the starting point.

2

y

The y co-ordinate of the starting point.

3

x1

The x co-ordinate of the end point.

4

y1

The y co-ordinate of the end point.

Return value

A linear gradient is drawn with the specified line to the shape drawn inside the Canvas element.

Example

The following example draws a simple gradient pattern to the rectangle drawn onto the Canvas element using HTML Canvas createLinearGradient() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var lineargrad = context.createLinearGradient(50, 50, 100, 100);
      context.fillStyle = lineargrad;
      lineargrad.addColorStop(0.05, 'red');
      lineargrad.addColorStop(0.95, 'orange');
      context.fillRect(25, 25, 150, 120);
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas CreateLinearGradient Method

Example

The following example adds gradient style to the rectangle drawn by the context object using three colors on the Canvas element.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var lineargrad = context.createLinearGradient(70, 50, 180, 110);
      context.fillStyle = lineargrad;
      lineargrad.addColorStop(0.25, 'yellow');
      lineargrad.addColorStop(0.5, 'orange');
      lineargrad.addColorStop(0.75, 'red');
      context.fillRect(25, 20, 200, 120);
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas CreateLinearGradient Method
html_canvas_colors_and_styles.htm
Advertisements