HTML and CSS Reference
In-Depth Information
Testing to See Whether the Browser Supports Canvas
Now that we have a reference to the
canvas
element on the HTML page, we need to test to
seewhetheritcontains a
context
.TheCanvascontext referstothedrawingsurfacedefinedby
a web browser to support Canvas. Simply put, if the context does not exist, neither does the
Canvas. There are several ways to test this. This first test looks to see whether the
getCon-
text
methodexistsbeforewecallitusingCanvas,aswehavealreadydefineditintheHTML
page:
iif
(
!
theCanvas
|| !
theCanvas
.
getContext
) {
return
return
;
}
Actually, this tests two things. First, it tests to see whether
theCanvas
does not contain
false
(the value returned by
document.getElementById()
if the named
id
does not exist). Then,
it tests whether the
getContext()
function exists.
The
return
statement breaks out and stops execution if the test fails.
Anothermethod—popularizedbyMarkPilgrimonhis
HTML5website
—usesafunctionwith
a test of a dummy canvas created for the sole purpose of seeing whether browser support ex-
ists:
function
function
canvasSupport
() {
return
return
!!
document
.
createElement
(
'canvas'
).
getContext
;
}
function
function
canvasApp
() {
iif
(
!
canvasSupport
) {
return
return
;
}
}
Our favorite method is to use the
modernizr.js
library
. Modernizr—an easy-to-use, light-
weight library for testing support for various web-based technologies—creates a set of static
Booleans that you can test against to see whether Canvas is supported.
To include
modernizr.js
in your HTML page, download the code from
ht-
tp://www.modernizr.com/
and then include the external
.js
file in your HTML page:
<
script src
=
"modernizr.js"
><
/script>
To test for Canvas, change the
canvasSupport()
function to look like this: