Canvas How to - Check if Canvas element is supported








Question

We would like to know how to check if Canvas element is supported.

Answer


<!--from   w ww .jav  a  2  s.c  o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var ct = document.getElementById('canvas');
    if ('getContext' in ct) {
        var ctx = ct.getContext('2d');
        //Rest of code
        console.log('Canvas supported');
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="300" height="300">Canvas not supported</canvas>
</body>
</html>

The code above is rendered as follows: