Alpha Transparency with the globalAlpha Property

We have chosen context.globalAlpha for this animation because it is very easy to explain and makes for an effective demonstration of animating on the Canvas. The globalAlpha property is the setting for transparency on the Canvas. The property accepts numbers from 0 through 1, representing a percentage of opaqueness for what will be drawn after the property is set. For example:

context.globalAlpha = 0;

The preceding code would set everything drawn afterward to be rendered 0% opaque, or completely transparent.

context.globalAlpha = 1;

The preceding code would set everything drawn afterwards to be rendered 100% opaque, or 0% transparent.

context.globalAlpha = .5;

The preceding code would set everything drawn afterwards to be rendered 50% opaque, or 50% transparent.

By manipulating these values over time, we can make things drawn onto the Canvas appear to fade in or out.

Note

context.globalAlpha affects everything drawn afterward, so if you don’t want something drawn with the globalAlpha property of the last thing drawn, you need to reset the value before drawing onto the Canvas.

Get HTML5 Canvas, 2nd Edition 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.