HTML5 Canvas: Adding gradients to shape

This entry is part 9 of 17 in the series HTML5 Canvas

Another effect you can use with canvas shapes is a gradient.

Gradient fills in the canvas can be created either through a linear (createLinearGradient) or radial (createRadialGradient) gradient.

To add colors to the gradient, use the addColorStop property.

<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title> Styling a square</title>
        canvas {
            border: 1px solid #000;
<canvas id='canvas' width='400' height='400'></canvas>
    var canvas = document.getElementById('canvas').getContext('2d');
    var grd = canvas.createLinearGradient(0, 200, 200, 0);
    grd.addColorStop(0, '#000');  // light blue
    grd.addColorStop(.5, '#ccc');  // dark blue
    grd.addColorStop(1, '#000');
    canvas.fillStyle = grd;
    canvas.strokeStyle = '#09c';
    canvas.lineWidth = 5;
    canvas.fillRect(0, 0, 200, 200);
    var grd = canvas.createRadialGradient(300, 250, 2, 200, 200, 250);
    grd.addColorStop(0, '#000');
    grd.addColorStop(1, '#ccc');
    canvas.fillStyle = grd;
    canvas.fillRect(200, 200, 200, 200);

Both gradient methods employ different parameters to control the behavior of the gradient, as shown here:

createLinearGradient(startX, startY, endX, endY)
createRadialGradient(startX, startY, startRadius, endX, endY, endRadius)

The radial gradient method can get a little complicated, so it is worth playing around with this; try adding various addColorStop to see what happens.

Series Navigation<< HTML5 Canvas: More effect methods
HTML5 Canvas: Drawing arcs or circles >>

Leave a comment

Leave a Reply