Fast html5 canvas on iPhone/mobile safari
I finally found a way to optimize 2d canvas drawing on the iPhone 4. Because of the retina display the canvas seems to be rescaled in a slow way (in software?). So even though the rendering itself is relatively fast, the end result is slow.
Setting the Viewport
The first step is to set the viewport scale to 0.5 which will result in having one pixel per css pixel.
<meta name="viewport" content="width=device-width, initial-scale=0.5, user-scalable=no"/>
So now the rendering is fast, but the picture is tiny.
3D transforms to the rescue
To scale the picture up we can use css 3d transforms which are fast.
canvas { -webkit-transform: scale3d(2, 2, 0) translate3d(200px, 110px, 0); }
Also note the translation to move the image back into place as it is being scaled from the origin.
That's it you got yourself a massive performance boost in about two lines of code. :)
Jonas Wagner
Sounds awesome, do you have any before/after FPS readings, or similar?
Comment by Paul Straw — 5/27/11 10:07 PM | # - re
I didn't add an FPS counter but it made the went from slow, to smooth. I'll add the counter now though. :)
Comment by Jonas Wagner — 5/27/11 10:33 PM | # - re
Where’s the demo?
Comment by Mathias — 5/31/11 8:50 AM | # - re
Great. I have made a beta test game on android with 25 frames/second. On iPhone it was 7 and it doesent work at all. With your trick i got it to 30-50 frames and it runs absolutly smooth. OK, it was not only the viewport. I also had a other concept of the game mainloop. On android a simple setInterval works very good. On the iPhone i had to call the mainloop itself with a setTimeout at the end.
How are you doing this?
Comment by Horst — 6/21/11 2:52 PM | # - re
You really should use requestAnimationFrame if it is available.
Comment by JulienW — 7/11/11 10:58 AM | # - re
full ack.
https://github.com/jwagner/webglice/blob/master/src/clock.js#L15 + a mapping for the vendor specific ones.
Comment by Jonas Wagner — 7/11/11 4:11 PM | # - re
Yes, CSS transform is definitely better than using width/height to scale!
Oh, and by the way, -webkit-transform-origin: 0 0;
Comment by zachstronaut — 7/11/11 7:21 PM | # - re
Thanks for the hint.
Comment by Jonas Wagner — 7/12/11 9:57 AM | # - re
Comment by Vladimir Grichina — 7/12/11 3:12 AM | # - re
Afaik - no. The iPhone renders the canvas at 4th the resolution anyway. The only difference is in the way it is scaled.
Comment by Jonas Wagner — 7/12/11 9:57 AM | # - re