Can browsers cause errors when trying to create a rendering context?

Can the following code cause an error?

var canvas = document.createElement("canvas"); var ctx = canvas.getContext("somethingwrong"); 

In chrome, it just returns null.

How would it be if the requested view context is known to the browser? (Like "webgl" or "experimental-webgl") Is there a way to eliminate errors? In chrome, I could not provoke this behavior.

In other words: do I need to wrap this code in try / catch in a library that checks purely for rendering context?

Maybe there is a way to objectify this? For instance. a web service that tries to dig through code in different browsers and lists them, possibly different results.

+5
source share
1 answer

Returning null is the expected behavior if the requested context is not available or if the canvas is already assigned to another type of context:

Returns null if the given context identifier is not supported, if the canvas has already been initialized with another type of context (for example, it tries to get the "2d" context after receiving the "webgl" context).

There are special cases where an exception may be related to proxy (ibid) scripts:

Throws an InvalidStateError exception if setContext() or the transferControlToProxy() methods are used.

In addition to this, although the browser may support a certain type of context, there is no guarantee that an object can be created if system resources, such as memory, are low, in which case null will be returned.

Below is an overview of what will be returned in different scenarios.

http://i.imgur.com/zqeZxv8.png

Thus, if you are not using proxies (which are not currently fully supported), you do not need to use try-catch with getContext() .

Tip. In the future, the canvas will receive the property probablySupportsContext() , which can be used before getContext() . This will do these tests and return false if the conditions are not met (supported context, already used with a different type of context, low resources, etc.):

 var supported = canvas . probablySupportsContext(contextId [, ... ] ) 

Returns false if the call to getContext() with the same arguments definitely returns null, and true otherwise.

Update I just wanted to dwell in detail on a special case - for specific extensions for suppliers it is theoretically possible to get an exception created depending on this particular extension and how it defines its behavior. But they should not be considered part of the standard and, since in most cases they are experimental, risk and non-standard behavior are implied.

+2
source

Source: https://habr.com/ru/post/1247335/


All Articles