HTML5 Game - Canvas Using Shadows

Introduction

There are four drawing state properties that we can use to add shadows to the shapes and text.

These properties are described in the following table.

Name Description Returns
shadowBlurSets the degree of blur in the shadownumber
shadowColor Sets the color of the shadow string
shadowOffsetX Sets the x-offset for the shadow number
shadowOffsetY Sets the y-offset for the shadow number

The following code adds shadows to shapes and text.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black}
            body > * {float:left;}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="140">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            //from  ww  w  .ja  va 2  s  . c om
            ctx.fillStyle = "lightgrey";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 3;
            
            ctx.shadowOffsetX = 5;
            ctx.shadowOffsetY = 5;
            ctx.shadowBlur = 5;
            ctx.shadowColor = "grey";
            
            ctx.strokeRect(250, 20, 100, 100);
            
            ctx.beginPath();
            ctx.arc(420, 70, 50, 0, Math.PI, true);
            ctx.stroke();
            
            ctx.beginPath();
            ctx.arc(420, 80, 40, 0, Math.PI, false);
            ctx.fill();
            
            ctx.font = "100px sans-serif";
            ctx.fillText("Hello", 10, 100);
            ctx.strokeText("Hello", 10, 100);
        </script>
    </body>
</html>

This example applies shadows to text, a rectangle, a complete circle and two arcs.

Related Topic