HTML5 Game - Canvas Using Transparency

Introduction

We can set the transparency of the text and shapes we draw in two ways.

The first is to specify a fillStyle or strokeStyle value using the rgba function instead of rgb.

We can also use the globalAlpha drawing state property, which is applied universally.

The following code shows the use of the globalAlpha property.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black}
            body > * {float:left;}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="300" height="120">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            /*from ww  w .  j  a v a 2  s.c om*/
            ctx.fillStyle = "lightgrey";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 3;
            
            ctx.font = "100px sans-serif";
            ctx.fillText("Hello", 10, 100);
            ctx.strokeText("Hello", 10, 100);       
            
            ctx.fillStyle = "red";
            ctx.globalAlpha = 0.5;
            ctx.fillRect(100, 10, 150, 100);
        </script>
    </body>
</html>

The value for the globalAlpha values may range from 0 (completely transparent) to 1 (completely opaque, which is the default value).

Related Topic