Monday, January 7, 2013

Found an HTML5 canvas shortcoming: Rotation

As I was working on the RaptorGL.com re-write I found the first noticeable shortcoming of the html5 canvas: rotation

To rotate a sprite on the canvas first we have to call context.save() then translate to the center point of the sprite or any other anchor point. After all this finally we can rotate the entire canvas... in radians. Not a big deal. We can easily convert angles into radians, but here comes the tricky part... what do you think the 0,0 (top,left) position of the canvas is now? If you said it's the center of the sprite then you're right. It took me a few tries to realize that it got moved around. Well now we have two options: call another context.translate or just use the context.drawImage and specify it there to save a function call. I chose the latter, and finally I can call context.restore(). As you can see that is a lot of extra function calls and steps just to rotate one sprite. 

Performance gets hit around 1000 sprites all rotating around at every frame. In the old implementation of RatorGL.com I had every sprite on its very own canvas and that canvas was drawn to the layer canvas. It sounds like a lot of work but it was all done in the background and only costs a little extra time at startup. That design could work in this case to eliminate many of the function calls if an object rotates once every second or so. I can see some optimizations there like group draw calls together for all the sprites that have the same rotation etc...

Since I'm set on entering into the Mozilla Game On Challenge with RaptorGL and also use it to write many of the games for the awesome One Game A Month Challenge I'm ok with FPS to drop to around 56 when rotating over 1000 sprites every frame
It’s not time for optimization yet :)