HTML and CSS Reference
In-Depth Information
Global Alpha and Text
UsingalphaisacoolwaytomakeobjectsseemtobepartiallyorfullytransparentonHTML5
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
;
Besidesthenow-familiarelementsthatweincludedformostoftheotherconfigurableoptions
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
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
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 the displayed text.
We will use another HTML5
range
control in our form, but this time we set the value range
with a
min
value of 0.0 and a
max
value of 1.0, stepping 0.01 every time the range is moved:
Alpha:
<input
<input type=
"range"
id=
"textAlpha"
min=
"0.0"