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

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>
<script>
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.beginPath();
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;
context.fill();
</script>

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>
<script>
var canvas = document.getElementById('opacity');
var context = canvas.getContext('2d');
context.beginPath();
context.arc(250, 110, 60, 0, 2 * Math.PI, false);
context.fillStyle = '#ff5632';
context.fill();
context.globalAlpha = 0.3;
context.beginPath();
context.arc(320, 110, 60, 0, 2 * Math.PI, false);
context.fillStyle = '#205032';
context.fill();
</script>

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

 


Related Content

vps germany
Disclaimer: The content published in this article is the views of the author only. Techglimpse does not gurantee accuracy, completness or validity. If you believe the content on this post violates your copyright, please send us a mail for removal. Read more.