Categories
Web development

HTML Canvas Shadows

HTML5 Canvas Shadows

To create shadow in HTML canvas use the shadowColor property together with the shadowBlur property.

The HTML canvas shadowColor property sets or returns the color to use for shadows.

Syntax:

context.shadowColor=color;

The HTML canvas shadowBlur property sets or returns the blur level for shadows.

Syntax:

context.shadowBlur=number;

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="shadow-blur" width="300" height="180" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("shadow-blur");
var ctx = c.getContext("2d");
ctx.shadowBlur = 30;
ctx.fillStyle = "#2a9d8f";

ctx.shadowColor = "black";
ctx.fillRect(30, 40, 100, 100);

ctx.shadowColor = "#264653";
ctx.fillRect(170, 40, 100, 100);
</script>

</body>
</html>

Output:


To adjust the shadow use the shadowOffsetX and shadowOffsetY properties.

The HTML canvas shadowOffsetX property sets or returns the horizontal distance of the shadow from the shape.

Syntax:

context.shadowOffsetX=number;

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="offset-x" width="200" height="200" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("offset-x");
var ctx = c.getContext("2d");
ctx.shadowBlur = 15;
ctx.shadowOffsetX = 25;
ctx.shadowColor = "black";
ctx.fillStyle= "#2a9d8f";
ctx.fillRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


The HTML canvas shadowOffsetY property sets or returns the vertical distance of the shadow from the shape.

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="offset-y" width="200" height="200" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("offset-y");
var ctx = c.getContext("2d");
ctx.shadowBlur = 15;
ctx.shadowOffsetY = 25;
ctx.shadowColor = "black";
ctx.fillStyle= "#2a9d8f";
ctx.fillRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


Enjoy coding!