title: HTML5 Canvas Performance and Optimization Tips, Tricks and Coding Best Practices
body: <h1>DO YOU KNOW SOME MORE BEST PRACTICES FOR CANVAS??</h1>
  <h2>Please add to this thread what you know, have learned, or have read online any and all Canvas best practices, tips/tricks for performance</h2>
  <p>With Canvas being still very new to internet, and no signs of it ever getting old that I can see in the future, there are not too many documented &quot;best practices&quot; or other really important tips that are a 'must know' for developing with it in any one particular place. Things like this are scattered around and many times on lesser known sites.</p>
  <p><strong>There's so many things that people need to know about, and still so much to learn about too.</strong></p>
  <hr />
  <p>I wanted to share some things to help people who are learning Canvas and maybe some who already know it quite well and am hoping to get some feedback from others about what they feel are some best practices or other tips and tricks for working with Canvas in HTML5.</p>
  <p>I want to start off with one I personally found to be quite a useful yet surprisingly uncommon thing for developers to do.</p>
  <h1>1. Indent your code</h1>
  <p>Just as you would any other time, in any other language whatever the case may be. It has been a best practice for everything else, and I have come to find that in a complex canvas app, things can get a little confusing when dealing with several different contexts and saved/restore states. Not to mention the code is just more readable and overall cleaner looking too.</p>
  <p>For example:</p>
  <pre><code>...
  // Try to tell me this doesn't make sense to do
  ctx.fillStyle = 'red';
  ctx.fill();
  ctx.save();
      if (thing &lt; 3) {
          // indenting
          ctx.beginPath();
              ctx.arc(2, 6, 11, 0, Math.PI*2, true);
          ctx.closePath();
          ctx.beginPath();
              ctx.moveTo(20, 40);
              ctx.lineTo(10, 200);
              ctx.moveTo(20, 40);
              ctx.lineTo(100, 40);
          ctx.closePath();
          ctx.save();
              ctx.fillStyle = 'blue'
              ctx.fill();
          ctx.restore();
      } else { 
          // no indenting
          ctx.drawImage(img, 0, 0, 200, 200);
          ctx.save();
          ctx.shadowBlur();
          ctx.beginPath();
          ctx.arc(2, 60, 10, 0, Math.PI*2, false);
          ctx.closePath();
          ctx.fillStyle 'green';
          ctx.fill();
          ctx.restore();
      }
  ctx.restore();
  ctx.drawRect();
  ctx.fill();
  ...
  </code></pre>
  <p>Is the IF statement not easier and cleaner to read and know what is what immediately going on than the ELSE statement in this? Can you see what I'm saying here? I think this should be a method that developers should continue to practice just as they would when writing plain 'ol javascript or any other language even.</p>
  <h1>Use requestAnimationFrame instead of setInterval / setTimeout</h1>
  <p>setInterval and setTimeout were never intended to be used as animation timers, they're just generic methods for calling functions after a time delay.  If you set an interval for 20ms in the future, but your queue of functions takes longer than that to execute, your timer won't fire until after these functions have completed.  That could be a while, which isn't ideal where animation is concerned. <strong>RequestAnimationFrame</strong> is a method which tells the browser that an animation is taking place, so it can optimize repaints accordingly.  It also throttles the animation for inactive tabs, so it won't kill your mobile device's battery if you leave it open in the background.</p>
  <p>Nicholas Zakas wrote a hugely detailed and informative <a href="http://www.nczonline.net/blog/2011/05/03/better-javascript-animations-with-requestanimationframe/" rel="noreferrer">article about requestAnimationFrame</a> on his blog which is well worth reading.  If you want some hard and fast implementation instructions, then <a href="http://paulirish.com/2011/requestanimationframe-for-smart-animating/" rel="noreferrer">Paul Irish has written a requestAnimationFrame shim</a> – this is what I've used in every one of the Canvas apps I have made until recently.</p>
  <h2>ACTUALLY</h2>
  <p>Even better than using requestAnimationFrame in place of setTimeout and setInterval, Joe Lambert has written a <a href="http://blog.joelambert.co.uk/2011/06/01/a-better-settimeoutsetinterval/" rel="noreferrer">NEW and improved shim</a> called requestInterval and requestTimeout, which he explains what issues exist when using requestAnimFrame.
  You can view the <a href="https://gist.github.com/1002116#file_request_interval.js" rel="noreferrer">gist of the script</a>.</p>
  <h2>ACTUALLY x2</h2>
  <p>Now that all the browsers have caught up on the spec for this, there has been an <a href="http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating" rel="noreferrer">update to the requestAnimFrame() polyfill</a>, one which will probably remain the one to use to cover all vendors.</p>
  <h1>Use more than one canvas</h1>
  <p>A technique for animation-heavy games which <a href="https://twitter.com/nicolahibbert" rel="noreferrer">@nicolahibbert</a> wrote about in a <a href="http://nicolahibbert.com/optimising-html5-canvas-games/" rel="noreferrer">post of hers on optimizing Canvas games</a> mentions that it may be better to use multiple canvasses layered on top of one another rather than do everything in a single canvas. Nicola explains that &quot;drawing too many pixels to the same canvas at the same time will cause your frame rate to fall through the floor. Take Breakout for example. Trying to draw the bricks, the ball, the paddle, any power-ups or weapons, and then each star in the background – this simply won't work, it takes too long to execute each of these instructions in turn. By splitting the starfield and the rest of the game onto separate canvases, you are able to ensure a decent framerate.&quot;</p>
  <h2>Render Elements Off-screen</h2>
  <p>I have had to do this for a few apps I've made including <a href="http://www.facebook.com/samsunggenomeproject/app_197458140327772" rel="noreferrer">Samsung's Olympic Genome Project facebook app</a>. It's an extremely useful thing to know and to make use of whether it's needed or not. It decreases load time immensely, plus it can be a really useful technique to load images off screen since they can sometimes take a while.</p>
  <pre><code>var tmpCanvas = document.createElement('canvas'),
      tmpCtx = tmpCanvas.getContext('2d'),
      img = document.createElement('img');
  
  img.onload = function() {
      tmpCtx.drawImage(thumbImg, 0, 0, 200, 200);
  };
  img.src = '/some/image/source.png';
  </code></pre>
  <p>Notice that the src of the image is set after it is loaded. This is a key thing to remember to do too. Once the images are done loading and drawn into these temp canvases, you can then draw them to your main canvas by using the same ctx.drawImage(), but instead of putting the image as the first argument, you use 'tmpCtx.canvas' to reference the temp canvas.</p>
  <h3>Other tips, tricks and resources</h3>
  <ul>
  <li><strong><a href="http://philip.html5.org/tests/canvas/suite/tests/" rel="noreferrer">Canvas test cases</a></strong></li>
  <li><strong><a href="http://kangax.github.com/jstests/" rel="noreferrer">Some more canvas and JS tests</a></strong></li>
  <li><strong><a href="http://www.html5rocks.com/en/tutorials/canvas/performance/" rel="noreferrer">HTML5Rocks performance Improving</a></strong></li>
  <li>**<a href="http://blog.digitalbackcountry.com/2012/05/using-requestanimationframe-to-optimize-dragging-events/" rel="noreferrer">requestAnimFrame to Optimize Dragging Events</a></li>
  </ul>
  <h3>Canvas has a back-reference</h3>
  <p>The 2d context has a back reference to it's associated DOM element:</p>
  <pre><code>var ctx = doc.getElementById('canvas').getContext('2d');
  console.log(ctx.canvas);    // HTMLCanvasElement
  </code></pre>
  <p>I'd love to hear more from other people on this. I am working on making a list of things that we should standardize to add a new section to my company's <a href="http://na.standards.com/standards" rel="noreferrer">Front-end Code Standards and Best Practices</a>. I'd love to get as much feedback on this as I can.</p>