HTML5 Canvas Tutorial: transparency

Canvas with transparent shapes

The degree of transparency of an object on a HTML5 canvas, we can set the globalAlpha property of the canvas context. The value of the globalAlpha property may be between 0 and 1 where 0 is total opacity and 1 total transparency.

context.globalAlpha=[value];

Example 1: Transparent object on a HTML5 Canvas. See image 1.

<!doctype html>
<html>
<head>
<title>Transparantie op HTML5 Canvas</title>
<script> 
  function drawAlpha() {
    var canvas = document.getElementById("alphaElements");
    var context = canvas.getContext("2d");
   
    context.beginPath();
    context.arc(170, 90, 60, 0, 2 * Math.PI, false);
    context.fillStyle = "red";
    context.fill();
	
	 context.globalAlpha = 0.5; // set global alpha
	 context.beginPath();
    context.arc(240, 120, 60, 0, 2 * Math.PI, false);
    context.fillStyle = "black";
    context.fill();
};
    window.addEventListener("load", drawAlpha, true);
</script>
</head>
<body>	
	<canvas id="alphaElements" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>
Rechthoek met schaduw op HTML5 Canvas
Image 1. Transparent object on HTML5 Canvas.

Check this example in your browser

Next tutorial

Leave a comment