Interested in optimizing your JavaScript code with canvas? I received a couple great optimized JavaScript implementations for my ball animation where I slated Flash vs Canvas. We’ll keep Flash out of this discussion for now, as it appeared to cloud some of the points I was attempting to get across. Don’t worry the Flash optimizations will come soon. Right now, let’s take a look at some canvas implementations.

First and foremost, I want to shout out a big thanks to the two submissions I received. Both David Wolever and John Bates took time out of their day to provid demos which perform much better than mine on mobile devices. As we run through this code, keep in mind the demos I created where using the EXACT same re-draw code in AS and JS. In order to fairly slate these optimizations against Flash, the ActionScript code should also get the opportunity for a makeover. There hasn’t been a single Flash developer that has thought my code was efficient. I was going for equality over raw efficiency but we’ll cover that another day. All of my results below are running the demos on a brand new iPod Touch.

First let’s take a look at David Wolevers code:
The key lesson here is that size matters. Additional testing showed that canvas performs better at 300×300 resolution (40fps) than it does at 500×500 resolution (22fps). Unfortunately the reverse is true and bumping up to 450×800 churns down to 17fps.

What is it about David’s example that performs so well? Actually, it’s quite genius, only clearing and redrawing the square of the canvas that changed. Essentially he follows the ball and only erases and redraws the ball. This is a great technique for optimizing, however, not very scalable. It takes our performance metrics at 500×500 and really measures performance redrawing 50×50. With one ball this is a great solution but with many balls, some clouds, and a background this technique will not work.

This technique is something that I hadn’t even considered doing and was a great submission. We’ll be doing some more scalability testing later showing how additional objects effect this implementation. Thanks again for the submission!

Next we’ll take a look at John Bates code based off of work by Kesiev:
This code rocked on my iPod touch at 47fps with 4 balls. He also rebuilt this demo using object oriented programming techniques and was able to get a consistent frame rate of ~39fps with up to 5 balls. The updated demo can be found here. Very interesting that object oriented code has such a dramatic effect on performance. It does also suffer from the same performance vs. size and runs at about 31fps at 800×500.

A bit besides the point but is there anyone that can tell me why this demo runs at 20fps in IE9 beta on my desktop? Might very well be an IE9 bug but they definitely tout the great performance of new standards. Overall John takes home the gold on providing a scalable demo that runs with 39fps at 500×500 pixels on my iPod Touch!

Conclusion:
We have had a couple great submissions and I would encourage those who have created code in SVG, CSS3 and canvas to send your demos my way. Overall, if you are creating small resolution animation canvas isn’t a bad choice. At higher resolutions though, it tends to bog down the phone and performance suffers. The good news, I have some great code to work with and am excited to start integrating some of these improvements into my JS canvas Box2D demo. Thanks again!

OK, I promised to leave Flash out, but… the question you should all be asking right now is: How does Flash performance differ by pixel resolution? Does it suffer from the same short comings as canvas? If you’d prefer not to know the answer please stop reading now.

For those of you who want the answer:
The flash demo runs at 57FPS at 800×800 resolution on my Nexus One. More on this at a later date, maybe tonight, maybe tomorrow but for sure by Wednesday. Keep checking back for more comparisons on mobile devices!

21 thoughts on “Optimizing JavaScript with Canvas for Mobile Devices

  1. “Actually, it’s quite genius, only clearing and redrawing the square of the canvas that changed. Essentially he follows the ball and only erases and redraws the ball. This is a great technique for optimizing, however, not very scalable. ”

    I’m confused. Flash has been doing this by default since Futurespash. Turn on “show redraw” to see yellow boxes indicating which rect has been updated.

  2. I’ll add the SVG statistic’s into a new post but we still have fragmentation as I can’t get any SVG demos to run on my Nexus One. The point behind this series of posts is that there isn’t currently a single technology that spans across two of the major mobile platforms. CSS3 is great on the iOS but doesn’t render correctly on the Android. SVG is great on the iOS but not on the Android. Canvas performs OK for small pixel sizes on both iOS and Android. Flash performs great on Android. There is still no overlap which was what I was hoping to get to through these conversations. Is there any technology that works great today on both iOS and Android?

  3. Exactly Jason! I would encourage everyone to right click and turn on redraw regions on my Flash demo. Notice how the ENTIRE screen is being redrawn. I did this purposefully to allow for an equal comparison. Almost EVERY JavaScript optimization I have received only redraws the area needed. Yes this is more optimized. However, it doesn’t show an accurate performance metric. The Flash would need to be optimized to do the same. My next demo will change EVERY pixel EVERY frame. That was the point of this example, the ball is just to show the frame rate and irrelevant to the performance comparison. Of course you can draw a subset of pixels at a faster frame rate. I’ll do a new post shortly that will clear this up. Animations most often change a large number of pixels making these demos completely relevant.

  4. Hey Chris,

    I can tell you why the SVG version is not showing up on a Android phone.
    SVG was not implemented because of size issues (or something like that).
    Of course there is no guarantee that even when implemented it will run as smooth as the IPod/IPhone version (That is the problem with multiple implementations of HTML for this kind of content). Also your demo is very simple. For more impressive demos you should look at some stuff at wonderfl.net and jsdo.it

  5. I’m confused about the purpose of such an alleged apples-to-apples comparison. Why should we care about the performance of non-optmized Flash vs. non-optimized JS in HTML5?

  6. Chris: I’m a bit skeptic about such abstract test cases. Essentially, your demo shows that full screen refreshing is faster in Flash than in Canvas. Even if you will now come up with a benchmark that changes every pixel in every frame, what will this benchmark tell us? Is this the kind of metric that determines which technology is better?

    There are so many other things that affect performance, eg: How large is the code that needs to be downloaded? How long does the browser need to initialise a canvas object vs. a flash object? How responsive is the finished program to user interaction? How well can the program adapt to the hardware (eg. draw a lower resolution version when running on a 3G iPhone vs a 3GS)?

    These are all factors that no benchmark will ever measure, and yet they will influence the perceived performance at least as much as raw frame rate comparisons.

  7. I’m reading a website by someone and supposed to take it seriously when you never considered that re-drawing a 50×50 sprite would be faster than redrawing a 500×500 screen?

    Goodbye.

  8. http://daringfireball.net/linked/2010/09/20/not-so-fast

    “Ends up the “HTML5” test was really, really poorly coded. Here’s a version that gets 45 FPS on my iPhone 4. Pays to be skeptical of any claim that Flash Player works well on mobile devices.

    UPDATE: Here’s another tweaked version of the canvas demo, this one from Charles Ying, that updates the FPS counter less frequently (to match the Flash version), which performs even better.”

    Adobe, LAZY, LIARS.

  9. “Actually, it’s quite genius, only clearing and redrawing the square of the canvas that changed. Essentially he follows the ball and only erases and redraws the ball. This is a great technique for optimizing, however, not very scalable. ”

    Another optimization would be to set the cacheAsBitmap for the ball object to true so that then the flash player will not recompute the pixels within the ball. It caches the pixels with alpha channel and pastes it into the area that it needs to move to. With it off flash would recompute the vector info f the ball movieclip and then render the pixels that changed because of the new vector overlay. That can have a drastic performance boost as the number of balls go up.

  10. All of the HTML / Flash comments that conclude with either being killed, dead, or made irrelevant are garbage.

    HTML vs Flash comments are about as interesting as Vanilla vs Chocolate comments. Oh, ok, you like vanilla, got it, goodbye.

  11. “I’ll add the SVG statistic’s into a new post but we still have fragmentation as I can’t get any SVG demos to run on my Nexus One. The point behind this series of posts is that there isn’t currently a single technology that spans across two of the major mobile platforms.”

    Please do add the SVG one. Flash only works on one platform… so why not show SVG?

    And please make them all only render what’s actually changed… that’s not “ingenious”, it’s perfectly normal and the only sane way to do any animation. In fact, for this demo you shouldn’t be doing any drawing at all from one frame to the next… you should be doing move operations, but I’m not sure if canvas or flash can do that.

    It seems pretty clear to me that canvas *does* work on all platforms. At my own web dev company, we have been gradually throwing out our flash animations and replacing them with javascript… our experience has been the javascript performs as good, if not better, in every case — and it gives us a lot more flexibility.

  12. The whole idea that HTML5 is ready to replace Flash is ludicrous.

    The whole reason Flash was developed was because Apple, Microsoft, Real, and others were all trying to make rich content their own proprietary mess. Flash solved this problem by providing a solution to producers, without bugging users with advertising like Real did.

    Now we have HTML5, which is great, don’t get me wrong – but it is nowhere near ready to replace flash.

    For starters, there is still no standardization. Microsoft, Apple, and Mozilla all have their own very particular ‘exceptions’ and ways of doing things to protect their interests. We don’t even have a standard video code yet thanks to Mozilla.

    Secondly, HTML5 has no hardware acceleration in any browser, rendering this much-welcomed and long-sought feature of modern video cards completely useless.

    Third, and probably most importantly, there are no significant authoring tools. In my HTML development, shapes get drawn not with a mouse but with primitive coding calls like quadraticCurveTo(). Text doesn’t get typed in an fonts/color changed in-place to best evaluate design considerations – all the fontography is specified in code.

    Want to move elements on HTML5 canvas? There is no mousing elements around, you calculate *relative* x/y coordinates in code.

    As a developer, I don’t mind wrapping my head around this as a learning experience for my first app or two – but down the road replacing Flash projects with HTML5 is going to double or triple my hours and platform debugging compared to Flash Professional at the very least.

    Not to mention all of the designers out there are are well-equipped and experienced in delivering quality Flash development with Flash Professional, but whom wouldn’t know where to begin with HTML5.

    Then there is the issue of variable-bitrate streaming – HTML5 doesn’t even have a specification for this, just Apple’s Live HTTP Streaming proposal. What’s funny is that Apple has neither released any Quicktime tools for producing this stream, except for a command-line segmenting tool – not open source – which only runs on MacOS and is buried in a link somewhere in their developer section.

  13. “It seems pretty clear to me that canvas *does* work on all platforms. At my own web dev company, we have been gradually throwing out our flash animations and replacing them with javascript… our experience has been the javascript performs as good, if not better, in every case — and it gives us a lot more flexibility.”

    Are you actually trying to imply that javascript animations will run as well as pre-compiled Flash? Or if you’re referring to using javascript in conjunction with the canvas element, presumably you are aware that over 40% of internet users using various Internet Explorer versions other than the recently released 9 beta won’t be able to see them, as there is no HTML5 support?

Comments are closed.