Canvas Text
Even if your browser supports the canvas API, it might not support the canvas text API. The canvas API grew over time, and the text functions were added late in the game. Some browsers shipped with canvas support before the text API was complete.
Checking for canvas text API support again uses
detection technique #2 (see Detection Techniques). If
your browser supports the canvas API, the
DOM object it creates to represent a <canvas>
element will have the getContext()
method (see Simple Shapes). If your browser doesnât support the canvas
API, the DOM object it creates for a
<canvas>
element will have only
the set of common properties, not anything canvas-specific. You can check
for canvas text support using this function:
function supports_canvas_text() { if (!supports_canvas()) { return false; } var dummy_canvas = document.createElement('canvas'); var context = dummy_canvas.getContext('2d'); return typeof context.fillText == 'function'; }
The function starts by checking for canvas support, using the
supports_canvas()
function introduced
in the previous section:
if (!supports_canvas()) { return false; }
If your browser doesnât support the canvas API, it certainly wonât support the canvas text API!
Next, you create a dummy <canvas>
element and get its drawing
context. This is guaranteed to work, because the supports_canvas()
function already checked that
the getContext()
method exists on all canvas objects:
var dummy_canvas = document.createElement('canvas'); var context ...
Get HTML5: Up and Running 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.