HTML5 Game - Canvas Shadow

Creating a shadow in canvas via four global properties.

We can create a shadow in canvas via four global properties.

These properties are:

  • shadowBlur
  • shadowOffsetX
  • shadowOffsetY
  • shadowColor

By default, the 2d rendering context does not draw shadows since shadowBlur, shadowOffsetX, and shadowOffsetY are set to 0, and shadowColor is set to transparent black.

To make a shadow appear, change the opacity of the shadowColor to non-transparent color, and set either shadowBlur, shadowOffsetX, or shadowOffsetY to a non-zero value:

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Pushing canvas further</title>
    <meta charset="utf-8">
    //from   ww w .  ja  va  2s  .  c om
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        // A basic drop shadow
        context.shadowBlur = 20;
        context.shadowColor = "rgb(0, 0, 0)";
        context.fillRect(50, 50, 100, 100);
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Note

The code above set the shadow a 20 pixel blur and have set its color to a fully opaque black.

The offset values for the shadow defaults to 0 pixels in the x direction, and 0 pixels in the y direction.

Related Topics