An example of using canvas shadows

Written by Richard Heyes, on 12th April 2013

A guide explaining how to use canvas shadows and also how they can be used to achieve a bevel effect.


[No canvas support]

The ability to add shadows allows you to easily make shapes that appear 3D-ish. They can be added to the shapes that you draw including text. Some examples are shown on the canvas here. The source code for which is below:

    window.onload = function (e)
        var context1 = document.getElementById('cvs1').getContext('2d');
        // Set the shadow properties that control the appearance of the shadow
        context.shadowColor   = '#666';
        context.shadowOffsetX = 3;
        context.shadowOffsetY = 3;
        context.shadowBlur    = 3;

        // Now draw two rectangles - one stroked one filled
        // Now draw a red circle with a different style shadow
        context.shadowColor = '#0a0';
        context.shadowOffsetX = 0;
        context.shadowOffsetY = 0;
        context.shadowBlur    = 25;
        context.fillStyle   = 'red';
        context.arc(150,30,25,0,2 * Math.PI, false);
        // And finally some text
        context.shadowColor = 'red';
        context.shadowOffsetX = 1;
        context.shadowOffsetY = 1;
        context.shadowBlur    = 1;
        context.font = '18pt Verdana';
        context.strokeText('A canvas shadow!', 10,90);

As you can see from the example there are four shadow properties that you can set:

The color sets the color of the shadow and can be named colors, hex values, rgb() values or rgba() values. The shadowBlur property should be a number and controls the extent of the blurring effect - zero is no blur. The shadowOffsetX and shadowOffsetY values control the offset to the shape that you're drawing. They can both be positive or negative - positive values go down and to the right whilst negative values go up and to the left.

Turning off shadows

To turn off shadows you can set the properties like so:

Inner shadows

Whilst you can set negative offsets for the direction of the shadow - you can't set negative blur to get an "inner-shadow". But using the clip() function you can achieve this effect:

The result will be that the outline that you draw just outside the clipped area will not be visible but the shadow (or at least - half of it) will fall inside and will be drawn. The resulting effect will be a bevelled appearance. In the code below the save() and restore() functions save the state of the canvas and then restore it. When restored the canvas will not be clipped anymore.

[No canvas support];
    context.fillStyle = 'red';
    context.arc(150,75,50, 0, Math.PI * 2, false)

    context.arc(150,75,50, 0, Math.PI * 2, false);

    context.strokeStyle = 'black';
    context.lineWidth = 5;
    context.shadowBlur = 15
    context.shadowColor = 'black';
    context.shadowOffsetX = 0;
    context.shadowOffsetY = 0;
    context.arc(150,75,50 + 3, 0, Math.PI * 2, false);