Canvas How to - Draw rectangle in transparency








Question

We would like to know how to draw rectangle in transparency.

Answer


<!--from ww  w  . java 2 s . co m-->
<!DOCTYPE HTML> <html> 
<head>
 <script> 
window.onload = function()
{ 
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   var xPos   = 20;   var yPos   = 20;   var gap = -20;
   var width  = 80;   var height = 80;

   context.shadowOffsetX = 4;
   context.shadowOffsetY = 4;
   context.shadowBlur    = 3;
   context.shadowColor   = "gray";

   context.globalAlpha = 1;
   context.fillStyle   = "orange";
   context.fillRect   (xPos+(0*width)+(0*gap), yPos, width, height);
   context.globalAlpha = .5; 
   context.fillStyle   = "blue";
   context.fillRect   (xPos+(1*width)+(1*gap), yPos, width, height); 
   context.globalAlpha = .25;
   context.fillStyle   = "red";
   context.fillRect   (xPos+(2*width)+(2*gap), yPos, width, height); 
   context.globalAlpha = .25;
   context.fillStyle   = "limegreen";
   context.fillRect   (xPos+(3*width)+(3*gap), yPos, width, height); 
   context.globalAlpha = .4;
   context.fillStyle   = "magenta";
   context.fillRect   (xPos+(4*width)+(4*gap), yPos, width, height); 
   context.globalAlpha = .25;
   context.fillStyle   = "gold";
   context.fillRect   (xPos+(5*width)+(5*gap), yPos, width, height); 
   context.globalAlpha = .4;
   context.fillStyle   = "turquoise";
   context.fillRect   (xPos+(6*width)+(6*gap), yPos, width, height);  
}
</script> 
</head> 
<body> 
<div    style  = "width:490px;   height:125px; 
                  margin:0 auto; padding:5px;">
<canvas id     = "canvasArea" 
        width  = "490"  height = "125" 
        style  = "border:2px solid black">
</canvas> 
</div> 
</body> 
</html>

The code above is rendered as follows: