HTML5 Game - Creating a radial gradient

Introduction

A radial gradient is created using the createRadialGradient method.

This method requires six arguments:

  • the first three describe one circle (the start circle),
  • and the last three describe another (the last circle).

These two circles describe not only the direction and where the gradient starts and ends, but also the shape of the gradient.

The three arguments that describe each circle are the (x , y) coordinate of the circle origin and the radius.

The arguments described as strings are:

createRadialGradient(x0, y0, r0, x1, y1, r1);  

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Pushing canvas further</title>
    <meta charset="utf-8">
    /*  w w w . jav  a 2s  .  c  o m*/
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
    let canvasCentreX = canvas.width()/2;  
    let canvasCentreY = canvas.height()/2;  
      
    let gradient = context.createRadialGradient(canvasCentreX, canvasCentreY, 0,  
    canvasCentreX, canvasCentreY, 250);  
    gradient.addColorStop(0, "rgb(0, 0, 0)");  
    gradient.addColorStop(1, "rgb(150, 150, 150)");  
      
    context.fillStyle = gradient;  
    context.fillRect(0, 0, canvas.width(), canvas.height());  
        
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topic