Shadow Effect on Canvas: HTML5


Today lets see how we can draw shadow on canvas elements like text, circle etc.

index.html and myStyle.css files are kept same as illustrated in previous video tutorial: Canvas State: HTML5

Since we’re showing shadow effect on Text, you need to first know how to draw text on canvas:
Draw Text on Canvas: HTML5
Draw Arcs/Circle with Canvas: HTML5

shadow-canvas-html5

Javascript file: Shadow settings
myScript.js

1
2
3
4
context.shadowColor     = "black";
context.shadowOffsetX   = - 10;
context.shadowOffsetY   = - 10;
context.shadowBlur      = 10;

using shadowColor we can set the color of the shadow. You can use any css color string as its value. By default, the color is transparent black.

shadowOffsetX and shadowOffsetY are used to set horizontal and vertical offsets of the shadow respectively. Both default to 0.

shadowBlur is the blurness of the shadow. It defaults to 0 too. Higher the value of shadowBlur, more blur it looks!

Javascript file: Full Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
 
context.shadowColor     = "black";
context.shadowOffsetX   = - 10;
context.shadowOffsetY   = - 10;
context.shadowBlur      = 10;
 
var myString            = "Microsoft";
context.font            = "40px Verdana strong";
context.textAlign       = "left";
context.strokeStyle     = "cyan";
context.fillStyle       = "blue";
context.textBaseline    = "bottom";
context.fillText(myString, 10, 100, 100);
context.strokeText(myString, 10, 100, 100);
 
 
context.arc(150, 150, 50, 0, 2 * Math.PI);
context.stroke();
 
}
}

Here we’re applying the shadow settings to text as well as a circle.

Draw Shadow on Canvas: HTML5


[youtube https://www.youtube.com/watch?v=Uj1oXQI4xaU]

YouTube Link: https://www.youtube.com/watch?v=Uj1oXQI4xaU [Watch the Video In Full Screen.]



We can apply shadow settings to text, circle, lines, arcs, images etc which is present on the canvas. Remember, you can’t directly apply CSS rules on canvas elements.

Leave a Reply

Your email address will not be published. Required fields are marked *