HTML5 Game - Canvas Global Alpha

Introduction

The value assigned to globalAlpha must range between 0.0 (transparent) and 1.0 (opaque).

The default value is 1.0.

The globalAlpha property will affect the transparency of the objects.

For example, you could draw a half transparent square like so:

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
               /* w  w w  . j  a  v  a 2s .  com*/
    context.fillStyle = "rgb(63, 169, 245)";  
    context.fillRect(50, 50, 100, 100);  
    context.globalAlpha = 0.5;  
    context.fillStyle = "rgb(255, 123, 172)";  
    context.fillRect(100, 100, 100, 100);  




  

            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

The code set the globalAlpha property after drawing the blue square, only the pink square will be affected by the alpha value.