Using Colors and Gradients with the HTML5 Canvas Tag

3 of 8 in Series: The Essentials of the HTML5 Canvas Tag

Nearly every operation in HTML5's canvas function implements a fill or stroke style. To get the most out of canvas, you need to understand how they work. The three primary types of styles you can use on fills and strokes are colors, gradients, and patterns.

Applying colors with the HTML5 canvas tag

To specify a fill or stroke color in the canvas tag, you can use the same color tools you use in CSS and HTML:

  • Six-digit hex values: The six-digit hexadecimal scheme commonly used in CSS uses two digits each for red, green, and blue. The value begins with a pound sign. For example, #FF0000 is red, and #FFFF00 is yellow.

  • Three-digit hex values: Hex color values often use repeating values, so you can abbreviate these values as three-digit numbers. In this scheme, red is #F00, and yellow is #FF0.

  • Color names: You can often use color names, like "red" or "yellow." Common color names will usually work, but not all browsers support the same list of color names; "papaya whip" is not likely to be supported.

  • RGB and RGBA values: You can use the rgb() function to create colors using integers (0–255) or percentages (0%–100%). Red is rgb(255, 0, 0) and yellow is rgb(100%, 100%, 0%). Note that the rgb function must go in quotes like any other color value. If you want to include alpha, add a fourth parameter, which is a zero–one value. Transparent red would be rgba(255, 0, 0, 0.5).

  • HSL and HSLA: The new hsl and hsla color formats are supposed to be supported by the canvas element, but so far, the support for these features varies by browser.

Note that the various values for a color are always enclosed in quotes. The color parameter is a string that can be interpreted as a CSS color.

Applying gradients with the HTML5 canvas tag

You can also fill a shape with a gradient. Canvas gradients are defined in two steps:

  • Create a gradient object. There are two methods built into the context object for this. One builds linear gradients, and the other builds radial gradients.

  • Add color stops. A color stop is a special element that indicates a color to be added to the gradient. You can add as many colors as you want, and you can also specify where along the gradient pattern the color will appear.

The following code builds a radial gradient and a linear gradient on a canvas:

    function draw(){
      var drawing = document.getElementById("drawing");
      var con = drawing.getContext("2d");
      
      //build a linear gradient
      lGrad = con.createLinearGradient(0,0,100,200);
      lGrad.addColorStop(0, "#FF0000");
      lGrad.addColorStop(.5, "#00FF00");
      lGrad.addColorStop(1, "#0000FF");
      
      con.fillStyle = lGrad;
      con.fillRect(0, 0, 100, 200);
      //build a radial gradient
      rGrad = con.createRadialGradient(150, 100, 
              0, 150, 100, 100);
      rGrad.addColorStop(0, "#FF0000");
      rGrad.addColorStop(.5, "#00FF00");
      rGrad.addColorStop(1, "#0000FF");
      con.fillStyle = rGrad;
      con.fillRect(100,0, 200, 200);
    } // end draw

The output of this code is shown here:

image0.jpg

A linear gradient is a pattern of colors that blend into each other along a straight-line path. To define a linear gradient, follow these steps:

  1. Create a variable to hold the gradient.

    Gradients are a little more complex than simple colors, so they are stored in variables to be reused.

  2. Build the gradient, using the createLinearGradient() method of the context object to build a linear gradient.

  3. Define the gradient path with the createLinearGradient() method.

    It expects four parameters that define a line (x1, y1, x2, y2). The colors will be perpendicular to this line, so if you want horizontal color bands, draw a vertical line. If you want vertical color bands, draw a horizontal line. The line typically takes up the entire width or height of the element, but it doesn't have to. If the line is smaller than the image, the excess area will be automatically assigned the color from the nearest end of the gradient.

  4. Add color stops.

    Gradients aren't much fun without colors. The addColorStop() method of the gradient object allows you to add a color to the gradient. Each color stop has two parameters: position and color. The position is a 0–1 value indicating where on the gradient line the color should be positioned. 0 is the beginning, 1 is the end, and intermediate values are in the middle. The color parameter is a text value that can be evaluated as a CSS color. At a minimum, you should define two color stops, one for the beginning and one for the end.

  5. Apply the gradient as a fill pattern.

    If you want to use the gradient as a fill pattern, set the context's fillStyle to the gradient variable you just created. All subsequent fills will be done using the gradient pattern (until the fillStyle is changed to something else).

Radial gradients are similar. Rather than drawing a gradient in a straight line, they draw a series of circular color bands. The first color is the center of the circle, and the last color defines an outer radius. Building a radial gradient is very similar to building a linear gradient. The only difference is the create command.

Use the console object's createRadialGradient() method to build a radial gradient. This command actually takes six parameters:

  • beginX: The X position of the starting point. This is often in the center of your shape.

  • beginY: Along with beginX, this determines the beginning position of your gradient.

  • beginRadius: The radius of your center circle. Usually this is zero, but you can make it larger if you want to emphasize the center color more.

  • endX: Describes the X position of the ending circle. Typically, this is the same as beginX.

  • endY: Along with endX, defines the position of the ending circle. If the beginning and ending circles have the same positions, you'll get a circular gradient. Change the ending position to make the gradient stretch in a particular direction.

  • endRadius: The ending radius defines where the last color gradient will be placed. Smaller values for this radius will lead to a tightly grouped gradient, and larger values will spread the gradient along a larger area.

Once the gradient is defined, the addColorStops() method works exactly like it does for linear gradients. The variable created through the addRadialGradient() command is usually stored in a variable, where it can be used for subsequent fillStyle() requests.

blog comments powered by Disqus
Advertisement

Inside Dummies.com