globalAlpha and RGBa in Canvas: HTML5

Today lets learn about globalAlpha and rgba properties of Canvas.

Lets draw 2 rectangle and apply rgba and see how it’ll be affected by globalAlpha setting.

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file
myScript.js

  context.globalAlpha = 0.5;
  
  context.fillStyle   = "rgba(255, 0, 0, 0.5)";
  context.fillRect(100, 100, 150, 50);
  
  context.fillStyle   = "blue";
  context.fillRect(100, 25, 150, 50);

Here we’ve set the globalAlpha value to 0.5, which will be applied to all the elements present on the canvas irrespective of its individual alpha values.
For Example: If we have a globalAlpha of 0.5 and we set individual alpha(using RGBa) to 0.5, then the individual element will have an alpha of 0.5 of it’s globalAlpha 0.5 i.e., half of the globalAlpha.

globalAlpha and RGBa in Canvas: HTML5



YouTube Link: https://www.youtube.com/watch?v=TtnGYP0AXd0 [Watch the Video In Full Screen.]



Note: globalAlpha and rgba take values from 0.0 to 1.0

JavaScript file: Full Code
myScript.js

window.onload = canvas;

function canvas()
{
 var myCanvas = document.getElementById("myCanvas");
 
 if( myCanvas && myCanvas.getContext("2d") ) 
 {
  var context         = myCanvas.getContext("2d");
  
  context.globalAlpha = 0.5;
  
  context.fillStyle   = "rgba(255, 0, 0, 0.5)";
  context.fillRect(100, 100, 150, 50);
  
  context.fillStyle   = "red";
  context.fillRect(100, 25, 150, 50);
 }
}

Take 2 rectangles with red color, so that you can easily compare the alpha differences between them, as you apply alpha value to them individually.

A canvas rgba() example:


window.onload = canvas;

function canvas()
{
 var myCanvas = document.getElementById("myCanvas");
 
 if( myCanvas && myCanvas.getContext("2d") ) 
 {
  var context         = myCanvas.getContext("2d");

  // Draw background
  context.fillStyle = 'rgb(255,221,0)';
  context.fillRect(0,0,150,37.5);
  context.fillStyle = 'rgb(102,204,0)';
  context.fillRect(0,37.5,150,37.5);
  context.fillStyle = 'rgb(0,153,255)';
  context.fillRect(0,75,150,37.5);
  context.fillStyle = 'rgb(255,51,0)';
  context.fillRect(0,112.5,150,37.5);

  // Draw semi transparent circles
  for (i=0;i<10;i++){
    context.fillStyle = 'rgba(255,255,255,'+(i+1)/10+')';
    for (j=0;j<4;j++){
      context.fillRect(5+i*14,5+j*37.5,14,27.5)
    }
  }
 }
}

Above code for self learning .. :-)