Canvas How to - Set transparent color with globalAlpha








Question

We would like to know how to set transparent color with globalAlpha.

Answer


<!--from  w w w  .  j ava2s  . c  om-->
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {  
        var canvas = $("#myCanvas");
        var context = canvas.get(0).getContext("2d");
        
        // Global alpha
        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="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

The code above is rendered as follows: