Badass JavaScript

A showcase of awesome JavaScript that pushes the boundaries of what's possible on the web, by @devongovett.

WebGL-2d: An Implementation of the 2d Canvas Context in WebGL

March 24th 2011

WebGL-2d is an interesting project that is aiming to be a complete port of the Canvas2D API implemented in a WebGL context as a proof of concept.  "Huh, why would anyone want to do that?“, you might be asking.  Currently, in supporting browsers, WebGL performs better in some scenarios than Canvas2D.  Specifically, WebGL often achieves much higher framerates in drawImage intensive code, leading to smoother animations in games and other such applications.

image

While WebGL is currently only supported in Firefox 4, Chrome 10, Opera 11, and WebKit nightly releases, WebGL-2d could be used to increase performance in those browsers while gracefully falling back to the native Canvas2D API in older browsers.  Thankfully, new browsers including IE9 and Firefox 4 are now hardware accelerating their Canvas2D implementations, so perhaps the need for a project like WebGL-2d will decrease in the near future.

The project currently supports a subset of the Canvas2D API, although enough for many applications.  See the Github project for a list of what is currently supported.  Switching your existing Canvas2D project to use the WebGL renderer through WebGL-2d easy and only requires one extra line of code:

var cvs = document.getElementById("myCanvas");

WebGL2D.enable(cvs); // adds "webgl-2d" context to cvs

var ctx = cvs.getContext("webgl-2d"); // easily switch between "webgl-2d" and "2d" contexts

Perhaps it isn’t entirely practical, but WebGL-2d is an interesting performance experiment nonetheless, and may be able to help improve the performance of canvas based games without having to change the code at all.  You can check out the WebGL-2d code, some benchmarks and examples on Github, and a demo of the project here.  Enjoy super-smooth animations!