HTML5 Game - Using Shadow Properties to Configure Shadows

Introduction

You can add shadows to lines, curves, shapes, and text using four core properties of the drawing context object:

  • shadowColor
  • shadowBlur
  • shadowOffsetX
  • shadowOffsetY

The shadowColor property indicates the color of the shadow.

The shadowBlur property is a numeric property and configures the blurriness of the shadow.

The lower the shadowBlur value, the sharper the shadow.

shadowBlur of 10 adds more blurriness to the shadow than a value of 5.

The shadowOffsetX and shadowOffsetY properties control the positioning of the shadow.

These x and y coordinates are relative to the target graphic object displaying the shadow.

Setting the shadowOffsetX and shadowOffsetY properties to 5 pixels, then the shadow is drawn 5 pixels to the right and 5 pixels down from the target graphic.

You can set shadowOffsetX and shadowOffsetY properties as negative numbers to shift the shadow in the opposite direction (left and up).

The following code adds shadows to a rectangle and text using the shadow properties discussed.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*from   www . ja v  a2s .  c  o  m*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        context.shadowColor = "#808080"; 
        context.shadowBlur = 5; 
        context.shadowOffsetX = 10; 
        context.shadowOffsetY = 10; 
        context.fillRect(20, 20, 150, 80); 
        
        context.shadowColor = "red"; 
        context.shadowBlur = 15; 
        context.shadowOffsetX = -5; 
        context.shadowOffsetY = 5; 
        context.fillStyle = "blue"; 
        context.textAlign = "center"; 
        context.font = "bold 30px Arial"; 
        context.fillText("Hello java2s.com!",100,150); 
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

This code draws a rectangle with a shadow color of #808080 and offsets of 10 pixels.

The blur value is 5.

The x offset value is -5, and shadowColor is red.

Related Topic