Linear Gradient

In this chapter you will learn:

  1. How to use the linear gradient
  2. Linear Gradient with a Smaller Shape

Using a Linear Gradient

<!DOCTYPE HTML><!--from  j  a v  a2 s.co m-->
<html>
<head>
<style>
canvas {
      border: thin solid black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="500"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            var grad = ctx.createLinearGradient(0, 0, 500, 140);
            grad.addColorStop(0.2, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");
            ctx.fillStyle = grad;
            ctx.fillRect(0, 20, 500, 140);
      </script>
</body>
</html>

Click to view the demo

Linear Gradient with a Smaller Shape

<!DOCTYPE HTML><!--from  jav a  2  s.  com-->
<html>
<head>
<style>
canvas {
      border: thin solid black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="140"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            var grad = ctx.createLinearGradient(0, 0, 500, 140);
            grad.addColorStop(0, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");
            ctx.fillStyle = grad;
            ctx.fillRect(10, 30, 50, 50);
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to use Radial Gradient
  2. Smaller shapes with a radial gradient
Home » Javascript Tutorial » Canvas
Canvas tag
Canvas Context
Rectangle
Rectangle clear
Drawing State
Drawing state restore
Line width
Line Join Style
Line cap settings
Gradients
Linear Gradient
Radial Gradient
Path
Arcs
Two types of curve
Quadratic Bezier Curves
Cubic Bezier Curves
Clip
Text
Shadow
Transparency
Stoke style