Rendering Linear Gradients using the HTML5 Canvas

Related HTML5 Canvas Posts:

Gradients are everywhere. They’re used to enhance toolbars or buttons and help add additional flare to a web page when used appropriately. In the past we’ve always had to rely on images to render gradients which works well, but isn’t necessarily the most efficient (although 1 pixel wide images do work well). CSS3 provides a great way to render gradients in modern browsers (see for a nice online gradient generator tool) but it’s not the only option. If you’re working with charts, games, multimedia or other HTML5 Canvas applications you can also use gradients and render them on the client-side without relying on images. In this post I’ll introduce how to use linear gradients and discuss the different functions that can be used to create them.


Creating Linear Gradients

Linear gradients can be created using the 2D context’s createLinearGradient function. The function takes the starting x,y coordinates and ending x,y coordinates of the gradient:


createLinearGradient(x1, y1, x2, y2);


By changing the start and end coordinates you can control the direction that the gradient renders. For example, adding the following coordinates causes the gradient to render from left to right since the y value stays at 0 for both points while the x value changes from 0 to 200.

var lgrad = ctx.createLinearGradient(0, 0, 200, 0);

Here’s an example of how changing the coordinates affects the gradient direction:



Once a linear gradient object has been created you can set color stops using the addColorStop() function. It takes the location where the color should appear in the gradient with 0 being the beginning and 1 being at the end (0.5 would be in the middle) as well as the color to display in the gradient.

lgrad.addColorStop(0, 'white');
lgrad.addColorStop(1, 'gray');


An example of combining createLinearGradient() with addColorStop() is shown next:


Using createLinearGradient()
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var lgrad = ctx.createLinearGradient(0, 0, 200, 0);
lgrad.addColorStop(0, 'white');
lgrad.addColorStop(1, 'gray');

ctx.fillStyle = lgrad;
ctx.fillRect(0, 0, 200, 200);
ctx.strokeRect(0, 0, 200, 200);

This code renders a white to gray gradient as shown next:


A live example of using createLinearGradient() is shown next. Click the Result tab to see the code in action.


In the next post on the HTML5 Canvas I’ll take a look at radial gradients and how they can be used. In the meantime, if you’re interested in learning more about the HTML5 Canvas and how it can be used in your Web or Windows 8 applications, check out my HTML5 Canvas Fundamentals course from Pluralsight. It has over 4 1/2 hours of canvas goodness packed in it.


comments powered by Disqus

No Comments