HTML5 Canvas Reference - globalAlpha








globalAlpha property of the Canvas context makes objects seem to be partially or fully transparent on HTML5 Canvas.

After globalAlpha is applied, it affects all drawing on the canvas.

The valid values for context.globalAlpha are numbers between 0.0 (transparent) and 1.0 (opaque), and they act as a percentage for the alpha value.

For example, a 50% alpha value would be coded like this:

context.globalAlpha = 0.5;

A 100% alpha (no transparency) would be coded like this:

context.globalAlpha = 1.0;

Browser compatibility

globalAlpha Yes Yes Yes Yes Yes




JavaScript syntax

context.globalAlpha=number;

Property Values

Value Description
number The transparency value. Must be a number between 0.0 and 1.0. 0.0 means fully transparent. 1.0 means no transparancy. Default value is 1.0

Example

The following code shows how to use globalAlpha to make an image transparent.

The image is like:


<!DOCTYPE html>
<html>
<body>
<canvas width="600" height="400"></canvas>
<script type='text/javascript'>
    var img = new Image;
    ctx = document.querySelector('canvas').getContext('2d');
    ctx.globalAlpha = 0.1;<!--from ww  w  .  j a  v a 2 s .  co  m-->
    img.onload=function(){
        ctx.drawImage(img,0,0);
    }
    img.src = "http://www.java2s.com/style/download.png";
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the transparency during the drawing.


<!DOCTYPE html>
<html>
<body>
<!--from w  w w .  j a v a2s  .  c  o m-->
<canvas id="myCanvas" width="300" height="150"></canvas>

<script>

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(20, 20, 75, 50);
    
    //Turn transparency on
    ctx.globalAlpha = 0.2;
    ctx.fillStyle = "blue"; 
    ctx.fillRect(50, 50, 75, 50); 
    
    //Change transparency
    ctx.globalAlpha = 1;
    ctx.fillStyle = "green"; 
    ctx.fillRect(80, 80, 75, 50);
</script>

</body>
</html>

The code above is rendered as follows: