How to detect HTML 5 [canvas] is not supported by JavaScript ?


There are a few ways to detect if HTML5 <canvas> is not supported by JavaScript:

  • Checking for canvas support using Modernizr library:

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user's browser. To check if the browser supports <canvas>, you can use the following code:

if (!Modernizr.canvas) {
  // canvas is not supported
}
  • Checking for canvas support using feature detection:

You can also use feature detection to check if the browser supports <canvas>. Here's an example:

var canvas = document.createElement('canvas');
if (!canvas.getContext) {
  // canvas is not supported
}
  • Checking for canvas support using try-catch block:

Another way to detect if <canvas> is supported is by using a try-catch block. Here's an example:

try {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
} catch (e) {
  // canvas is not supported
}

If the browser does not support <canvas>, an exception will be thrown and caught by the catch block.

It's important to note that <canvas> is supported by all modern browsers, so it's unlikely that you'll need to check for support. However, if you're developing for older browsers or specific devices, it may be necessary to check for support.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.