HTML5 Game - Setting the Transparency of a Drawing Object

Introduction

You can change the transparency of a graphic object using the strokeStyle and fillStyle properties.

These properties can set a transparency level.

This is accomplished using the rgba() function.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*from www  .  j  av a 2  s  . c  o m*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
       context.fillStyle = "black"; 
       context.fillRect(20, 20, 150, 80); 
       context.fillStyle = "rgb(255, 0, 0)"; 
       context.fillRect(40, 40, 150, 80); 
  
       context.fillStyle = "black"; 
       context.fillRect(20, 150, 150, 80); 
       context.fillStyle = "rgba(255, 0, 0,0.5)"; 
       context.fillRect(40, 170, 150, 80); 

    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

The first block of code draws two filled rectangles without any transparency.

The second block of code draws two filled rectangles with the second rectangle having a transparency of 50%.

The fourth parameter of rgba() is the alpha value.

It controls the transparency.

The alpha value can be between 0 to 1, 0 being transparent and 1 being opaque.

Related Topic