HTML5 Game - Drawing a Linear Gradient

Introduction

A gradient sets a range of colors used to fill a shape.

The gradient effect sets color ranges between the start and end positions.

A gradient can be of two types : linear or radial.

A linear gradient is defined by two points and a color at each of those points.

A radial gradient is defined by two circles, each of which has a color.

To use gradient, create a corresponding gradient object and then define the required color stops.

Finally, fill a shape with the fillStyle property set to the gradient object.

The following code shows how you can fill a rectangle with a linear gradient.

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  . j  a  va2 s  . co m
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        let linearGradient = context.createLinearGradient(0, 100, 200, 100); 
        linearGradient.addColorStop(0, "blue"); 
        linearGradient.addColorStop(0.5, "green"); 
        linearGradient.addColorStop(1, "red"); 
        context.fillStyle = linearGradient; 
        context.fillRect(0, 0, 200, 200); 

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

Note

This code creates a linear gradient object via context's createLinearGradient() method.

The first two parameters of createLinearGradient() represent the x and y coordinates of the gradient's start point.

The last two parameters represent the x and y coordinates of the end point.

The gradient is drawn from the start point to the end point.

The code adds three further color stops.

The color-stop offset values range from 0 to 1, from the start of the gradient to the end.

The drawing context's fillStyle property is set to the linear gradient object.

Related Topic