You can use Matt's suggestion. I've also found the following works:
var canvasSupported = "HTMLCanvasElement" in window;
Latest Firefox, Chrome & Opera return true
, all IEs return false
.
To clarify, this method makes use of the HTMLCanvasElement class that derives from the HTMLElement class exposed by the browser -- IE8 exposes these classes in standards mode only, IE9 will expose them in IE8 and IE9 standards modes.
This feels more like "feature detection" to me, you're asking if something exists, not trying to create it and then asking if creating it worked. The latter is also not as efficient. This is something to consider when including many similar methods in a large library that is for use along with other scripts on a page, you want to squeeze as much performance as possible.
A blog post from the IE9 team appeared today which reminded me of this answer. It's interesting to me that posting it caused a bit of controversy, considering that it was accepted and then later the acceptance was transferred to a different answer. Here we are 4 months later and an official blog post from the aforementioned vendor recommends this method:
In addition to HTML markup, support for , , and can also be detected from script. This detection can be performed many ways, but one of the simplest is to check for the existence of the appropriate interface object off of window.
// Example 7: Simple feature detection for
if(window.HTMLCanvasElement) {
// Code requiring canvas support
}
This is virtually identical to the method I suggested here. The only difference is the truthy/falsey check, instead of the property in object check. Granted, they do suggest the check for getContext as an alternative, but I thought it worth updating this answer for those who might want to use an alternative to creating a dummy element and not using it.