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
Javascript file: Shadow settings
myScript.js
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
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
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.