Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas Element and IE

Well not just IE, any browser that doesn't currently support it

I want to start using the processing.js framework. It's used for making images with the canvas element. However I'm reluctant to use it due to the fact that it's not widely supported.

So what's the best way for me to give the user an alternative image if they do not support the canvas element?

I'd need something like...

if(!canvas){
    element.style.backgroundColor = 'red';
}

Is there a standardised way of doing this yet? If not what's the best thing I could do?

like image 309
Ben Shelock Avatar asked Nov 17 '25 21:11

Ben Shelock


1 Answers

Any content between the <canvas></canvas> tags will be displayed if the canvas element is not supported. So you can try:

<canvas><img src="alt-image-for-old-browsers.png" /></canvas>

The logical thing that comes to mind is to place the JavaScript you want to run between the <canvas></canvas> tags:

<canvas>
  <script>
  document.getElementById('element').style.backgroundColor = 'red';
  </script>
</canvas>

But alas this doesn't work. Even browsers that support the Canvas API will execute the script.

So perhaps the best thing you can do to programatically check that the browser supports the canvas API is to check the getContext method available on all <canvas></canvas> elements:

function supportsCanvasAPI() {
  var canvas = document.createElement('canvas');
  if (window.G_vmlCanvasManager) { // IE ExplorerCanvas lib included?
    G_vmlCanvasManager.initElement(canvas);
  }
  return 'getContext' in canvas
}

That creates a dummy canvas (so as to not worry about grabbing a reference to one in the DOM already) and checks if the getContext property exists on the element. It also checks to see if ExplorerCanvas has been included for IE. It won't tell you exactly what features of the API are supported (beyond the standard set of shapes, paths, etc).

An article on feature-detecting HTML5 features (like canvas) can be found here.

like image 199
Crescent Fresh Avatar answered Nov 20 '25 10:11

Crescent Fresh