Jagan N
Jagan N

Reputation: 2065

How to handle canvas unavailability in javascript?

I've a html page that uses HTML 5 canvas. I've used the below code for creating canvas object.

<canvas id="testCanvas" width="200" height="200">
    Canvas Not Supported
</canvas>

This works as expected and displays the text "Canvas Not Supported" in browsers like IE 8. However, there is a problem with the below javascript associated with the canvas.

<script>
    var testCanvas = document.getElementById("testCanvas");
    var testCanvasContext = testCanvas.getContext("2d");
</script> 

The above code throws an error message Object doesn't support this property or method in browsers that don't support canvas. What's the correct approach to handle this in javascript?

Please do not suggest to use libraries like excanvas.

Upvotes: 1

Views: 337

Answers (3)

user1693593
user1693593

Reputation:

In your script you can test for the definition of canvas:

if (typeof HTMLCanvasElement !== "undefined") {
  // get canvas and context here
}
else {
  // sorry, canvas not supported in this browser
}

An alternative is to use:

if ("HTMLCanvasElement" in window) {
  // get canvas and context here
}
else {
  // sorry, canvas not supported in this browser
}

Also, when the canvas element is obtained you should check for getContext's return value. This is because can only provide one type of context at a time (f.ex. "2d" vs "webgl"):

var context = canvas.getContext("2d");
if (context) { /* all OK */ }

Upvotes: 1

PeterMader
PeterMader

Reputation: 7285

I would use a try/catch block:

function getContext(canvas){
  try {
    // return the context or null
    return (canvas.getContext && canvas.getContext('2d')) || null;
  } catch (e) {
    // an error occured; return null
    return null;
  }
}

var testCanvas = document.getElementById("testCanvas");
var testCanvasContext = getContext(testCanvas);
if (testCanvasContext) {
  // supported
} else {
  // not supported
}

Upvotes: 1

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

TRY with the following :

<script>
   var testCanvas = document.getElementById("testCanvas");
   var testCanvasContext = window.CanvasRenderingContext2D && testCanvas.getContext("2d");
   if (testCanvasContext) {
      // do stuff
   }
</script>

Upvotes: 1

Related Questions