Radial Gradient

In this chapter you will learn:

  1. How to use Radial Gradient
  2. Smaller shapes with a radial gradient

Use Radial Gradient

We define radial gradients using two circles. The start of the gradient is defined by the first circle, the end of the gradient by the second circle.

The six arguments to the createRadialGradient method represent:

  • The first and second arguments are coordinate for the center of the start circle.
  • The third argument is radius of the start circle
  • The fourth and fifth arguments is coordinate for the center of the finish circle
  • The sixth argument is radius of the finish circle
<!DOCTYPE HTML><!--  jav a  2s  .c o m-->
<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.createRadialGradient(250, 70, 20, 200, 60, 100);
            grad.addColorStop(0.2, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");
            ctx.fillStyle = grad;
            ctx.fillRect(20, 20, 500, 140);
      </script>
</body>
</html>

Click to view the demo

Smaller shapes with a radial gradient

<!DOCTYPE HTML><!--   ja va2 s  .c  om-->
<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.createRadialGradient(250, 70, 20, 200, 60, 100);
            grad.addColorStop(0.2, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");
            ctx.fillStyle = grad;
            ctx.fillRect(100, 20, 75, 50);
            ctx.lineWidth = 8;
            ctx.strokeStyle = grad;
            ctx.strokeRect(200, 20, 75, 50);
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. What are the methods we can use the draw path
  2. How to draw a path with lines
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