Read my book

I wrote books about Webpack and React. Check them out!

Tuesday, April 26, 2011

Testing Canvas API Calls

This post was inspired by this question at StackOverflow. Basically the author wanted to verify that certain calls have been made while using the HTML5 Canvas API. I came up with a little solution.


Here's the code in its entirety:

In order to verify that something has happened we need to record each call made somehow. This can be done by wrapping actual API calls with some logic that does just this. Since the Canvas API may not be introspected dynamically, each method to be tested has to be declared explicitly. There's some overhead but not too much.

General Remarks

In addition I defined a specific method for handling assignments. It would be nice to use the same API here. Sadly there does not appear to be any standard way to achieve this as far as I know. Mozilla provides __defineSetter__ but that's about it as far as I know. Feel free to prove me wrong!

You can use the same pattern to wrap and test your own class-based APIs. Just monkey-patch the recorder within your API and you are good to go.

This kind of testing makes it possible to test and implement something like relative coordinates (0.2 instead of 100px etc.) with quite a little effort. Just set up some scheme and assert the output.


This type of testing misses some vital bits related to Canvas in particular. It is possible to inspect the color of an individual pixel using getImageData method of the API.

In addition it would be a good idea to test how the algorithms you are using work across browsers. Basically you'll want to set up some way to capture output of various browsers and then compare them using your favorite tool such as ImageMagick.

The latter way is particularly suitable for testing against regressions during development. Stash output per version somewhere so you can compare against it later.