globalAlpha and RGBa in Canvas: HTML5

Advertisement:

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

1
2
3
4
5
6
7
		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


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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:

rgba canvas html5 technotip globalAlpha and RGBa in Canvas: HTML5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
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 .. icon smile globalAlpha and RGBa in Canvas: HTML5

Advertisement:

Enter your email address:

RSS Feed




Leave a Reply