HTML5 Canvas Reference - shadowBlur








The shadowBlur property sets or gets the blur level for shadows.

To create a shadowEffect, there are four properties of the Canvas context that need to be manipulated:

  • context.shadowColor
    The color of the shadow. This uses the same "#RRGGBB" format of the fill Style and strokeStyle properties.
  • context.shadowOffsetX
    The x offset of shadow. This can be a positive or negative number.
  • context.shadowOffsetY
    The y offset of shadow. This can be a positive or negative number.
  • context.shadowBlur
    The blur filter diffusion of the shadow. The higher the number, the more diffusion.

To create a red shadow that is 5 pixels to the right and 5 pixels down from your text, with a blur of 2 pixels, you would set the properties like this:

context.shadowColor  = "#FF0000"; 
context.shadowOffsetX  = 5; 
context.shadowOffsetY  = 5; 
context.shadowBlur  = 2;




Browser compatibility

shadowBlur Yes Yes Yes Yes Yes

JavaScript syntax

context.shadowBlur= number;

Property Values

Value Description
number Default value is 0. The blur level for the shadow

Example

The following code fills a red rectangle with a black shadow, with blur level of 20:


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.shadowBlur = 20;<!--from   w ww  .ja v  a2s  .  c o  m-->
    ctx.shadowColor = "black";
    ctx.fillStyle = "red";
    ctx.fillRect(20, 20, 200, 80);

</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code adds shadow to a rectangle.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='200px' height='200px'/>
<script type='text/javascript'>
var ctx = document.getElementById("canvas").getContext("2d");
    ctx.shadowColor = 'black';
    ctx.shadowBlur = 15;<!--from   w  w  w  .j a v  a  2s.co  m-->
    ctx.strokeRect(20, 30, 150, 75);


</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code adds shadows to a circle.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='200px' height='200px'/>
<script type='text/javascript'>
var context = document.getElementById("canvas").getContext("2d");
    // Add shadow to canvas
    context.shadowOffsetX = 5;<!--from  w  w w .  ja  va2  s . co m-->
    context.shadowOffsetY = 5;
    context.shadowBlur = 4;
    context.shadowColor = 'rgba(30,30,30, 0.5)';
    // Draw circle (blue)
    context.beginPath();
    context.arc(50, 50, 40, 0, 2 * Math.PI, false);
    context.fillStyle = "#00f";
    context.fill();


</script>
</body>
</html>

The code above is rendered as follows: