HTML5 Game - Drawing a Radial Gradient

Introduction

You use the createRadialGradient() method to create a radial gradient object.

You supply coordinates for the center of the start and end circles along with their respective radii.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){//from   w  w  w .  jav  a2s.  co  m
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        let radialGradient = context.createRadialGradient(100, 100, 5,100, 100,100); 
        radialGradient.addColorStop(0, "blue"); 
        radialGradient.addColorStop(0.5, "green"); 
        radialGradient.addColorStop(1, "red"); 
        context.fillStyle = radialGradient; 
        context.fillRect(0, 0, 200, 200); 


    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

The createRadialGradient() method takes six parameters.

The first three represent the coordinates of the start circle (100,100) and its radius (5).

The next three indicate the coordinates of the end circle (100,100) and its radius (100).

The gradient starts out blue, then turns green, and then changes to red due to color stop values of 0, 0.5, and 1.

Related Topic