How to create a gradient (HTML)

Applies to Windows and Windows Phone

Shapes and lines aren’t limited to solid colors. A gradient used in canvas is actually a type of color value, so you can apply it to fillStyle and strokeStyle properties.

Gradients can be used to produce a directional change in intensity or color in an image. This is useful for producing background images, indicating altitude in maps, or anywhere you want to add lighting and shading to a surface.

Gradients are useful in streamlining your web apps as you can avoid using images for these effects and minimize the bandwidth and the time it takes to load them. And because they are produced programmatically they can be scaled and reused easily.

Prerequisites

This topic assumes that you can create a basic Windows Store app using JavaScript that uses the Windows Library for JavaScript template. For instructions on creating your first Windows Store app using JavaScript, see Create Your First Web App. For instructions on using the WinJS template, see How To Obtain and Use the WinJS Toolkit.

Instructions

Step 1: Obtain the rendering context

Before we can draw an image to our canvas, and color our image with a gradient, we need to obtain the rendering context from the canvas element. The rendering context is where all the drawing methods and properties are defined.

  1. To improve the performance of the Windows Store app using JavaScript wait until the HTML page has loaded before executing the JavaScript code. Do that by placing the code that will draw the image in a function that is called after the page has loaded.
    window.onload = drawGradient;   
    
    function drawGradient() {...
    
    
  2. Use the getElementById to retrieve the canvas Document Object Model (DOM) node and then use the getContext method to access the rendering context.

    There are different types of rendering contexts that enable you to draw in different ways. For example, there’s a 2-D context for 2-D graphics and a 3-D context for 3-D graphics. The examples in this topic use the 2-D rendering context.

        // Get the canvas element and specify a 2d drawing context.
        var context = document.getElementById("canvas").getContext("2d");
    
    

Step 2: Create the gradient

Once we have the rendering context we can define the gradient. There are two types of gradients; linear, or a straight gradient, and radial, or circular.

Linear gradient

The linear gradient method uses four arguments:

createLinearGradient(startX, startY, endX, endY)
The first set of two arguments are the x and y position of the start of the gradient, and the second set of arguments are the x and y position of the end of the gradient.
  • Vertical linear gradient

    In this example the createLinearGradient method is assigned to the myGradient variable. This will be useful in the next step when we add colors to the gradient.

    var myGradient=context.createLinearGradient(0, 0, 200, 0);
    

    To create a vertical linear gradient, where the gradient shades from one side to the other, the starting x and y positions of the gradient are set at 0 and 0, while the ending x and y positions are set at 200 and 0. Because the y values (the 2nd and 4th parameters) are both 0, the gradient shades evenly from left to right.

    A vertical gradient.

  • A Horizontal Gradient

    To create a gradient that shades from top to bottom, keep the x values (1ST and 3RD parameters) constant, and make the y values (2ND and 4TH parameters) range from 0 to the height of the canvas.

    var myGradient=context.createLinearGradient(0, 0, 0, 100);
    

    A horizontal gradient

  • A Diagonal Gradient

    You can also create gradients along a diagonal. In this example both the x and y values vary, set at 200, and 100 respectively.

    var myGradient=context.createLinearGradient(0, 0, 200, 100);
    

    A diagonal gradient

Radial gradient

The createRadialGradient method uses six arguments:

createRadialGradient(startX, startY, startRadius, endX, endY, endRadius)
Where the parameters are:
  • startX and startY are the x and y coordinates on the canvas for the starting circle.
  • startRadius is the radius of the starting circle.
  • endX and endY are the x and y coordinates on the canvas for the ending circle.
  • endRadius is the radius of the ending circle.
  • A traditional radial gradient

    To create a "traditional" radial gradient, where the color fades evenly from one circle to the other, you need to set the x/y coordinates of both circles to the same value, and make sure that one of the gradient circles is larger than the other.

    var myGradient = context.createRadialGradient(52, 50, 10, 52, 50, 200);
    
    

    A radial gradient.

  • Different start and end locations

    In the previous radial gradient example, the x/y coordinates are the same for both the starting and ending location at 52 and 50, respectively and only the size of the radius for each circle has increased, from 10 to 200. This centers the shading of the radial gradient in the center of the circle.

    If you move the start and end locations even further apart you will end up with a cone like gradient stretched across the canvas.

    var myGradient = context.createRadialGradient(32, 30, 5, 60, 60, 50);
    
    

    In this example, the starting circle x/y coordinates are 32 and 30, and it has a radius of 5. And the ending circle x/y coordinates are at 60 and 60, and with a larger radius of 50. Here is the result:

    A radial gradient with different x/y coordinates.

Step 3: Set the color stops

A gradient has two or more addColorStop methods:

addColorStop(offset, color)

To add a color stop, you need to specify the color to be applied, and its offset position along the gradient. Gradient positions can be anywhere between 0, at the start of the gradient, to 1, at the end of the gradient.

In our example, the myGradient var is used to set the addColorStop from 0 to 1 so that the gradient shades evenly from white to black.

myGradient.addColorStop(0,"white");
myGradient.addColorStop(1,"black");
  • Multiple color stops

    You can use multiple color stops. In this example a second addColorStop assigns a color stop half way across the gradient:

      myGradient.addColorStop(0,"orange");
      myGradient.addColorStop(.5, "green");
      myGradient.addColorStop(1, "blue");
    

    Will produce this gradient:

    A multi-colored vertical gradient.

Step 4: Set the fill style

Before drawing the gradient, the fillStyle must be set to the myGradient.

context.fillStyle = myGradient;

Lastly the fillRect method is used to draw the image:

context.fillRect(0, 0, 200, 100);

Complete Examples

Linear gradient

This JavaScript code uses a canvas element to draw a rectangle and then uses a diagonal linear gradient for the rectangle's fillStyle.

window.onload = drawGradient;   

function drawGradient() {

    // Get the canvas element and specify a 2d drawing context.
    var context = document.getElementById("canvas").getContext("2d");

    // Create a linear gradient.
    var myGradient=context.createLinearGradient(0, 0, 300, 100);

    // Set the color stops.
    myGradient.addColorStop(0, "white");
    myGradient.addColorStop(1, "black");

    // Set the fill style to the gradient.
    context.fillStyle = myGradient;

    // Draw the rectangle.
    context.fillRect(0, 0, 200, 100);
}

Radial gradient

This JavaScript code uses a canvas element to draw circle and then uses a radial gradient for the circle's fillStyle.

window.onload = drawGradient;   

function drawGradient() {

    // Get the canvas element and specify a 2d drawing context.
    var context = document.getElementById("canvas").getContext("2d");
  
    // Create the radial gradient.
    var myGradient = context.createRadialGradient(52, 50, 10, 52, 50, 200);

    // Set the color stops.
    myGradient.addColorStop(0, "white");
    myGradient.addColorStop(1, "black");

    // Set the fill style to the gradient.	   
    context.fillStyle = myGradient;

    // Draw a circle.
    context.beginPath();
    context.arc(52, 50, 40, 0, Math.PI*2, true); 
    context.closePath();
    context.fill();
}

Cascading Style Sheets (CSS)

This is an example of a CSS that creates a grey border around a canvas element.

/* Style the canvas element with a grey border. */
canvas { border: 1px solid #c3c3c3; }

HTML file

This HTML file creates a canvas element and uses external JavaScript and CSS files.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="myJavascript.js"></script>
        <link Rel="stylesheet" Href="myStyle.css" Type="text/css">
    </head>
    <body>
        <canvas id="canvas" width="200" height="100" />
    </body>
</html>

Related topics

Quickstart: Drawing to a canvas
Optimizing performance: JavaScript code

 

 

Show:
© 2014 Microsoft