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'>
<head>
    <meta charset='utf-8'>
    <title>Codecrawl.com: Styling a square</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
<canvas id='canvas' width='400' height='400'></canvas>
<script>
    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);
    canvas.closePath();
    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);
    canvas.closePath();
</script>
</body>
</html>

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.

CSS3: Making buttons with CSS gradients

This entry is part 3 of 13 in the series CSS3

Using CSS3, we can design some nice subtle buttons without any images.

As the gradients are scalable, you will find that it is actually less hassle to design buttons using CSS3 than to use images.

<!DOCTYPE html>
<html>
<head lang='en'>
    <meta charset='UTF-8'>
    <title>Codecrawl.com - CSS3</title>
    <style>
        div.container {
            height: 200px;
            width: 200px;
            background: -moz-linear-gradient(white, black);
            background: -webkit-linear-gradient(white, black);
            background: linear-gradient(white, black);
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }
    </style>
</head>
<body>

<div class='container'>
    <p>Oversized Button</p>
</div>

</body>
</html>

Line 10 above is for Mozilla Firefox.  Line 11 is for Safari and Chrome webkit.  Line 12 is the official CSS3 gradient.

The white and black inside the brackets are the start and stop colors of the gradient.