Creating Shadows on Canvas Shapes
We can add shadows to shapes we draw on the canvas by using four parameters. As with the tiled fill patterns in the previous section, this feature has not been fully implemented on all HTML5-compliant browsers.
We add a shadow by setting four Canvas properties:
shadowOffsetX
shadowOffsetY
shadowBlur
shadowColor
The shadowOffsetX
and shadowOffsetY
values can be positive or
negative. Negative values will create shadows to the left and top rather
than to the bottom and right. The shadowBlur
property sets the size of the
blurring effect on the shadow. None of these three parameters is affected
by the current Canvas transformation matrix. The shadowColor
property can be any color set via
HTML4 color constant string—rgb()
or
rgba()
—or with a string containing a
hex value.
Example 2-27 and Figure 2-39 show a few different boxes drawn with various shadow settings.
Figure 2-39. Adding shadows to drawn objects
Example 2-27. Adding shadows to drawn objects
function
drawScreen
()
{
context
.
fillStyle
=
'red'
;
context
.
shadowOffsetX
=
-
4
;
context
.
shadowOffsetY
=
-
4
;
context
.
shadowColor
=
'black'
;
context
.
shadowBlur
=
4
;
context
.
fillRect
(
10
,
10
,
100
,
100
);
context
.
shadowOffsetX
=
−
4
;
context
.
shadowOffsetY
=
−
4
;
context
.
shadowColor
=
'black'
;
context
.
shadowBlur
=
4
;
context
.
fillRect
(
150
,
10
,
100
,
100
);
context
.
shadowOffsetX
=
10
;
context
.
shadowOffsetY
=
10
;
context
.
shadowColor
=
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.