A proposal for using Canvas in web workers

[2012-11-18] dev, html5, javascript, clientjs
(Ad, please don’t block)
Ian Hickson, editor of the HTML spec, has proposed a way to let web workers use Canvas.

In the browser, all “normal” work happens in a single thread. That means that the user interface and computing tasks are competing for processor time. Thus, if you don’t want to block the user interface, you perform computationally intensive tasks in a background thread, via web workers (see section below). Creating bitmap graphics is a common activity on the web and a candidate for being done in the background. The easiest solution would be to make Canvas (HTML element and bitmap API), available to workers. But that is not possible, because they don’t have access to the DOM and Canvas cannot exist independently of it. Quoting Ian Hickson:

I was faced with two options:
  • Option A: Provide an API for off-screen graphics in workers, requiring that every frame you package the whole thing up, send it over to the main thread, and blt it there.
  • Option B: Provide a mechanism by which a worker can actually paint directly onto a main thread <canvas> element.
I ended up specifying something that lets you do both. You can instantiate a CanvasRenderingContext2D object anywhere, including a worker;
  • (A) when a rendering context is not bound to a specific canvas, it can be used as an off-screen drawing surface.
  • (B) You can then bind such a rendering context to a canvas; when you do this, there is a commit() method that you can use which tells the user agent to push the bitmap drawn on the CanvasRenderingContext2D object to the canvas bitmap / screen.

Material on web workers