HTML Canvas - addColorStop() Method



The HTML Canvas addColorStop() method can be used to add new color to some part of the graphics rendered on the Canvas element.

It belongs to the canvasGradient interface and is used by all the gradient types to provide color input at the particular position of the graphic on the Canvas element.

Syntax

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

canvasGradient.addColorStop(offset_value, color);

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1

offset_value

It takes a value between '0' and '1', inclusive which represents the position of the color stop. '0' represents the start of the gradient to apply color and '1' represents the end.

2

color

The color to be applied with the specified offset_value.

Return value

It applies gradient colors to a graphic drawn on the Canvas element and renders the result directly on the canvas.

Example 1

The following example draws a simple gradient patterned graphic onto the Canvas element using HTML Canvas addColorStop() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var grad = context.createLinearGradient(0, 0, 200, 100);
      context.fillStyle = grad;
      grad.addColorStop(0.3, 'blue');
      grad.addColorStop(0.5, 'grey');
      grad.addColorStop(0.7, 'purple');
      context.fillRect(30, 10, 190, 80);
   </script>
</body>
</html>

Output

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

HTML Canvas AddColorStop Method

Example 2

The following program draws a rectangle onto the Canvas element and applies color pattern using addColorStop() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var grad = context.createLinearGradient(0, 0, 200, 100);
      context.fillStyle = grad;
      grad.addColorStop(0.25, 'purple');
      grad.addColorStop(0.90, 'cyan');
      context.fillRect(30, 10, 190, 80);
   </script>
</body>
</html>

Output

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

HTML Canvas AddColorStop Method
html_canvas_colors_and_styles.htm
Advertisements