...

View Full Version : Determine, the browser supports canvas (paperjs) or not



dadli88
06-22-2012, 10:21 PM
Hello.
Please tell, how can i determine, the browser supports canvas (paperjs), or not ?

mrhoo
06-22-2012, 11:07 PM
function testCanvas(){
var canvas= document.createElement('canvas'),
test= !!canvas.getContext;
canvas= null;
return test;
}

dadli88
06-22-2012, 11:23 PM
Thanks, but tell please, which means that two exclamation here:
test= !!canvas.getContext;
?

venegal
06-23-2012, 03:31 AM
!! basically converts anything to a boolean. ! is the logical NOT operator, so it will convert a falsy value to true and a truthy value to false. Doing this two times in a row will make falsy values false and truthy values true.

I'd recommend using Modernizr's detection method, though, which is

function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}

I don't know enough about the cross-browser pitfalls of canvas to tell you which browser fails the other check, but if they are doing it this way, it can't be a bad idea.

(I don't quite get the reason for the canvas= null in that other snippet it doesn't do anything.)

mrhoo
06-23-2012, 05:04 AM
I don't quite get the reason for the canvas= null

It does nothing in many browsers, but there are some browsers who's memory usage increases with every new html element created by a script, even those elements that are not added to the document tree. If you don't care about that, you can make a simpler test and call it just once-


function hasCanvas(){
return !!document.createElement('canvas').getContext;
}

venegal
06-23-2012, 12:38 PM
It does nothing in many browsers, but there are some browsers who's memory usage increases with every new html element created by a script, even those elements that are not added to the document tree.


Do you have some documentation on the behavior canvas= null is a workaround for? I can't quite imagine a situation where this would make a difference the reference would be removed at the end of the function anyway, since converting to boolean prevents the forming of a closure, so I don't see how, after the function has run, there's any difference a browser bug could act upon.

Btw, the additional elem.getContext('2d') check seems to be necessary for some mobile devices.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum