Falcon80 Logo
Shadows on canvas

In addition to filling an area with specific colours or colour gradients, you can also fill it with an image to create patterns. You can use the createPattern() method to do this.

You can add a shadow to both images and text using the shadowOffsetX and shadowOffsetY attributes.

shadowOffsetX = number of pixels offset in the x direction;
shadowOffsetY = number of pixels offset in the y direction;

Adding a blur effect to the shadows will make it more realistic.

shadowBlur = number of pixels to be blured in the x and y direction;

eg:

ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 4;
ctx.strokeText("Believe", 0,0);

You can also specify the color of the shadow using the shadowColor attribute.

shadowColor = "colour of the shadow";

You could either directly specify the colour of the shadow or provide values for red, green and blue in hexadecimal or decimal.

eg: Provide the color directly:
shadowColor="green";

provide the value of red, green, and blue in hexadecimal:
shadowColor="00FF00";

provide the value of red, green and blue in decimal:
shadowColor="rgb(0,255,0)";

Provide the value of red, green and blue in decimal along with the level of transparency desired:
shadowColor="rgba(0,255,0,0.5)";

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var ctx = canvas.getContext("2d");

// Define the number of pixels offset in the X and Y directions
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
// Define the blur width
ctx.shadowBlur = 4;
// Define the colour of the shadow
ctx.shadowColor = "grey";

// Try the shadow on a rectangle
ctx.fillStyle= "green";
ctx.fillRect(50,50,100,100);

// Try the shadow on text
ctx.font="40px verdana";
ctx.textBaseline="top";
ctx.fillText("Believe", 250,50)

// Try the shadow on an image
var flower = new Image();
flower.src="../../Images/Attributes/flower.png";
ctx.drawImage(flower, 500,50);

}
}
  </script>
  <title>Styles and colours on canvas</title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code