Friday 4 January 2013

Your HTML5 canvas spritesheets may not work on iOS Safari

So, I was working on a game that had all it's assets packed into a (relatively huge) spritesheet that was 4096x4096 in dimensions.

Since my iPod (my only iOS device) was out of charge, I only tested it on my Android phone. It worked smoothly, and I went along happily. Later, when I finally got to see if it worked on iOS, it mysteriously didn't. Now, I knew that sometimes canceling touchmove events messes with it firing click events and so on, so I tried the usual things I do to debug the problem. It didn't help. I simplified the problem to just this much code:





All that does is load a random spritesheet I found using Google Images, and then draw a 300x300 slice from that spritesheet once the image has been loaded. You can see this in action here, and from my testing, it works in Chrome and Firefox (both on desktop, and on Android).




The above fiddle should look like the image on the right when it works, and the image has had time to be loaded. If you see only a tiny black square on the top left, it means the image has been loaded, and if your browser / device is good enough, it should be displaying the clipped part too. On iOS on my iPod, it doesn't. For reference, this is what it looks like on a browser where it works:




I did find that when my spritesheet was reduced from 4096x4096 to 2000x2000, it started working on the iPhone 5, but it didn't on the iPod. So, pretty clearly, there's something strange going on with Safari on iOS. I'd recommend you to avoid using spritesheets till issues like this one are sorted.

Oh, also, iOS Safari doesn't throw any errors when it fails to draw a slice of the spritesheet. It fails silently, leaving you to wonder what the heck went wrong.