HTML5 Game - Set drawing via Transparency

Introduction

Object transparency is created by using the globalAlpha attribute.

This attribute indicates the degree of transparency from 0 to 1.

0 is fully transparent and 1 is fully opaque.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
<head>
<script>
//Draws object with transparency on a canvas.
window.onload = function() {/*from w w w .ja va 2s  .  co  m*/

    canvas = document.getElementById("canvasArea");
    context = canvas.getContext("2d");

    //LAYOUT of first object.
    let xPos = 20;
    let yPos = 20;
    let gap = -20;
    let width = 80;
    let height = 80;

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

    // A9. OBJECTS with global alpha.
    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">
You're browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

Related Topic