Global Alpha and Text
Using alpha is a cool way to make objects seem to be partially or fully
transparent on HTML5 Canvas. The globalAlpha
property of the Canvas context is
used for this purpose. After globalAlpha
is applied, it affects all drawing
on the canvas, so you need to be careful when setting it.
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
;
Besides the now-familiar elements that we included for most of the
other configurable options in Text Arranger, the globalAlpha
property requires us to think a
bit more about when we use it and how it will affect the rest of the
canvas.
First, we create a variable named textAlpha
in the canvasApp()
function and initialize it with
1
, which means the text will have no
transparency when it is first displayed:
var
textAlpha
=
1
;
Next, in the drawImage()
function, we need to set the globalAlpha
property twice—once before we draw
the background and the bounding box frame:
function
drawScreen
()
{
//Background
context
.
globalAlpha
=
1
;
And then again to the value stored in textAlpha
, just before rendering the text to
the canvas:
context
.
globalAlpha
=
textAlpha
;
This will reset globalAlpha
so that we can draw the background, but it will still allow us to use a configurable alpha value for ...
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.