简体   繁体   中英

HTML5 Canvas Context

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.

doesn't tell me what other (if any) contexts might be available.

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" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM