Drawing transparent shapes

For applications that require shape layering, it's often desirable to work with transparencies. In this recipe, we will learn how to set shape transparencies using the global alpha composite.

Drawing transparent shapes

How to do it...

Follow these steps to draw a transparent circle on top of an opaque square:

  1. Define a 2D canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Draw a rectangle:
        // draw rectangle
        context.beginPath();
        context.rect(240, 30, 130, 130);
        context.fillStyle = "blue";
        context.fill();
  3. Set the global alpha of the canvas using the globalAlpha property and ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.