问题描述
我已经开始阅读/试验HTML5。我见过的所有关于HTML5 Canvas的教程都遵循JavaScript的模式,通过ID获取画布,获取2d上下文,然后处理上下文:
类似于
您只调用一次 getContext ,如果再次调用它如果画布已经用不同的上下文类型初始化,它将返回null。如果使用相同的上下文类型再次调用它,它将返回相同的上下文。如果画布不支持给定的上下文ID字符串,则返回空值。
换句话说,每个画布只有一个上下文。
为此,有一个方法 supportsContext(someContextString),这对于尚未在任何浏览器中实现的spec(2012年3月)来说是非常新颖的。
另外还有 setContext ,这在任何浏览器中都还不支持(可能会在几个晚上)。请注意, setContext 仅在您创建了无头环境时才有用,因为如果尝试使用已经具有上下文(通过使用getContext)的上下文,则该画布会引发错误设置一个不同的。
无论如何,参数是一个字符串的原因是允许对画布进行特定于浏览器的扩展。毕竟,MS可能想实现 getContext('2d-directx')(他们可能永远都不会这样做)。
您现在看到的唯一字符串是2d,webgl和webgl-experimental。
I have started reading/experimenting with HTML5. All the tutorials I've seen for the HTML5 Canvas follow the pattern of JavaScript getting the canvas by ID, getting a 2d context, and then working with the context:
<canvas id="myCanvas" width="300" height="200" style="border:1px solid"></canvas> <script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="cyan"; ctx.fillRect(50,50,100,75); </script>I was wondering if there is any enumeration or constants for getting a Context for the Canvas.
Something like Context.2D, Context.3D, etc. (I know this isn't a real constant, just wondering if there is something like it somewhere in JavaScript or HTML5).
Every example I've seen, the call that is made is simply getContext("2d"). This seems brittle, and also doesn't tell me what other (if any) contexts might be available.
解决方案You call getContext only once, and if you call it again it will return null if the canvas has already been initialized with a different context type. If you call it again with the same context type, it will return the same context. Null is also returned if a canvas does not support a given context ID string.
In other words, each canvas has only one context.
For this there is the method supportsContext(someContextString), which is very new to the spec (March 2012) that has yet to be implemented in any browser.
There's additionally setContext that is not yet supported in any browser (might be in a few nightlies). Note that setContext is only useful if you've made a headless context, because a canvas that already has a context (via use of getContext) will throw an error if you try to set a different one.
Anyway, the reason that the argument is a string is to allow for browser-specific extensions to the canvas. After all, MS might want to implement getContext('2d-directx') (they probably would never actually do this).
The only strings you'll see these days are "2d", "webgl", and "webgl-experimental".
这篇关于HTML5画布上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!