HTML5 Canvas Tutorial: strokes & fills

Canvas with rectangle and shadow

For creating shadows in a HTML5 canvas, we can use the shadowOffsetX and shadowOffsetY properties of the canvas context.

context.shadowOffsetX=[value];
context.shadowOffsetY=[value];

Example 1: Rectangle with shadow on the HTML5 Canvas. See image 1.

<!doctype html>
<html>
<head>
<title>Schaduweffecten op HTML5 Canvas</title>
<script> 
 window.onload = function(){
    var canvas = document.getElementById("shadow");
    var context = canvas.getContext("2d");
 
    context.rect(100, 50, 200, 100);
    context.fillStyle = "#f16529";
    context.shadowColor = "#999999";
    context.shadowBlur = 15;
    context.shadowOffsetX = 10;
    context.shadowOffsetY = 10;
    context.fill();
};
</script>
</head>
<body>	
	<canvas id="shadow" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>
Rectangle with shadow on the HTML5 Canvas
Image 1. Rectangle with shadow on the HTML5 Canvas

Check this example in your browser

Similarly, we can apply the shadow effect on other characters, such as a semicircle

Example 2: Circle with shadow on an HTML5 Canvas. See also image 2.

<!doctype html>
<html>
<head>
<title>Schaduweffecten (cirkel) op HTML5 Canvas</title>
<script> 
    function drawCircle()
    {
        var canvas=document.getElementById("shadow");
        var context=canvas.getContext("2d");
 
        var centerX = 175;
        var centerY = 100;
        var radius = 70;
 
        context.beginPath();
        context.arc(centerX,centerY,radius,0, Math.PI,false);
        context.closePath();
 
        context.fillStyle="#f16529";
		 context.shadowColor = "#999999";
   		 context.shadowBlur = 15;
   		 context.shadowOffsetX = 10;
  	     context.shadowOffsetY = 10;
        context.fill();
       
    }
    window.addEventListener("load", drawCircle, true);
</script>
</head>
<body>	
	<canvas id="shadow" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>

Cirkel met schaduw op HTML5 Canvas
Image 2. Circle with shadow on an HTML5 Canvas.

Check this example in your browser

Next tutorial

Leave a comment