How to add Shadow and Global Alpha to elements in Canvas? [Basics]

Updated on September 3, 2017

We saw how to create shapes in HTML5 Canvas and also decorated it with gradient fills. What if you want to add a shadow or Global Alpha effect to shapes? You can do that using shadowColor, shadowBlurshadowOffsetX and shadowOffsetY properties of the canvas context.

For demonstration purpose, lets create a circle using Arc() method, use fillStyle property to set color for the circle, shadowColor property to set the color of the shadow, shadowBlur property to set the level of the shadow, shadowOffset property for the x and y coordinates; to define the shadow position.

Lets see the code below to that adds shadow to a circle.

canvas tutorial

<canvas id="shadow" width="500" height="200"></canvas>
var canvas = document.getElementById('shadow');
var context = canvas.getContext('2d');
var center_X = canvas.width / 2;
var center_Y = canvas.height / 2;
var radius = 80;
context.arc(center_X, center_Y, radius, 0, 2 * Math.PI, false);
context.fillStyle = '#cb4025';
context.shadowColor = '#bde7f8';
context.shadowBlur = 20;
context.shadowOffsetX = 15;
context.shadowOffsetY = 10;

Global Alpha

In Order to set opacity to elements in HTML5 Canvas, you can use globalAlpha property. The value can be a real number anywhere between ‘0’ and ‘1’; where ‘0’ is fully transparent and ‘1’ is fully opaque.

For demonstration, lets create two overlapped circles; where one with opacity adjustment.

<canvas id="opacity" width="578" height="200"></canvas>
var canvas = document.getElementById('opacity');
var context = canvas.getContext('2d');
context.arc(250, 110, 60, 0, 2 * Math.PI, false);
context.fillStyle = '#ff5632';
context.globalAlpha = 0.3;
context.arc(320, 110, 60, 0, 2 * Math.PI, false);
context.fillStyle = '#205032';

That’s it! Checkout the demo and if you liked the post, please share it with HTML5 community.


Was this article helpful?

Related Articles

Leave a Comment