Radial Gradients in Canvas: HTML5

Lets see how radial gradients are drawn on canvas using HTML5.

For Radial Gradients, we take 2 circles, one is the interior to the other. Thus, one circle is bigger than the other.

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file: Radial Gradient
myScript.js

  var rdl              = context.createRadialGradient(125, 125, 50, 125, 125, 100);
  rdl.addColorStop(0.0, "#f00");  // RED
  rdl.addColorStop(0.5, "#00f");  // BLUE
  rdl.addColorStop(1.0, "#0f0");  // GREEN

                context.beginPath();
  context.fillStyle    = rdl;
  context.arc(125, 125, 100, 0, 2 * Math.PI);
  context.fill();

We make use of createRadialGradient method and draw 2 circles at 125px x-axis and 125px y-axis as center. With radius of 50 and 100 each. i.e., First circle is inside the second circle.
Now using addColorStop we add different colors at different points.

addColorStop() takes 2 parameter, first being the position and the next being any valid css color string.

The value of position can range from 0.0 to 1.0

at point 0% we take red – #f00
at point 50% we take blue – #00f
at point 100% we take green – #0f0

Radial Gradients in Canvas: HTML5



YouTube Link: https://www.youtube.com/watch?v=DfbA1h36MDw [Watch the Video In Full Screen.]



We assign the radial gradient object rdl to the fillStyle of circle present on canvas.

JavaScript file: Full Code
myScript.js

window.onload = canvas;

function canvas()
{
 var myCanvas = document.getElementById("myCanvas");
 
 if( myCanvas && myCanvas.getContext("2d") ) 
 {
  var context         = myCanvas.getContext("2d");
  
  var rdl                = context.createRadialGradient(125, 125, 50, 125, 125, 100);
  rdl.addColorStop(0.0, "#f00");  // RED
  rdl.addColorStop(0.5, "#00f");  // BLUE
  rdl.addColorStop(1.0, "#0f0");  // GREEN
  
  context.shadowColor     = "#000";   // BLACK
  context.shadowBlur      = 10;
  
  context.beginPath();
  context.lineWidth       = 2;
  context.strokeStyle     = "pink";
  context.fillStyle       = rdl;
  context.arc(125, 125, 100, 0, 2 * Math.PI);
  context.stroke();
  context.fill();
 }
}

We add shadow to the circle and stroke it with pink color border.

Note: We change the gradient radially by changing the center point of the inner circle.