Advertisement
Guest User

Untitled

a guest
Dec 5th, 2013
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 88.54 KB | None | 0 0
  1.  
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5.    
  6.     <title>javascript - HTML5 Canvas Performance and Optimization Tips, Tricks and Coding Best Practices - Stack Overflow</title>
  7.     <link rel="shortcut icon" href="//cdn.sstatic.net/stackoverflow/img/favicon.ico">
  8.     <link rel="apple-touch-icon image_src" href="//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">
  9.     <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml">
  10.     <meta name="twitter:card" content="summary">
  11.     <meta name="twitter:domain" content="stackoverflow.com"/>
  12.     <meta name="og:type" content="website" />
  13.     <meta name="og:image" content="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=fde65a5a78c6"/>
  14.     <meta name="og:title" content="HTML5 Canvas Performance and Optimization Tips, Tricks and Coding Best Practices" />
  15.     <meta name="og:description" content="DO YOU KNOW SOME MORE BEST PRACTICES FOR CANVAS??
  16. Please add to this thread what you know, have learned, or have read online any and all Canvas best practices, tips/tricks for performance
  17. With Ca..." />
  18.     <meta name="og:url" content="http://stackoverflow.com/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices"/>
  19.     <link rel="canonical" href="http://stackoverflow.com/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices" />
  20.  
  21.    
  22.    
  23.     <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  24.     <script src="//cdn.sstatic.net/Js/stub.en.js?v=0c501610f52c" type="text/javascript"></script>
  25.     <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/stackoverflow/all.css?v=6a89240d9097">
  26.    
  27.     <script type="text/javascript">
  28.        
  29.         StackExchange.ready(function () {
  30.             StackExchange.using("postValidation", function () {
  31.                 StackExchange.postValidation.initOnBlurAndSubmit($('#post-form'), 2, 'answer');
  32.             });
  33.  
  34.            
  35.             StackExchange.question.init({votesCast:[],canViewVoteCounts:true,totalCommentCount:0,shownCommentCount:0,highlightColor:'#F4A83D',backgroundColor:'#FFF',questionId:8205828});
  36.  
  37.             styleCode();
  38.  
  39.                 StackExchange.realtime.subscribeToQuestion('1', '8205828');
  40.            
  41.                     });
  42.     </script>
  43.  
  44.  
  45.     <script type="text/javascript">
  46.         StackExchange.ready(function () {
  47.             StackExchange.realtime.init('wss://qa.sockets.stackexchange.com,ws://qa.sockets.stackexchange.com');
  48.             StackExchange.realtime.subscribeToInboxNotifications();
  49.                     StackExchange.realtime.subscribeToReputationNotifications('1');
  50.                             StackExchange.realtime.subscribeToTopBarNotifications('1');
  51.         });
  52.     </script>
  53.     <script type="text/javascript">
  54.         StackExchange.init({"locale":"en","stackAuthUrl":"https://stackauth.com","serverTime":1386237136,"styleCode":true,"enableUserHovercards":true,"site":{"name":"Stack Overflow","description":"Q&A for professional and enthusiast programmers","isNoticesTabEnabled":true,"recaptchaPublicKey":"6LdchgIAAAAAAJwGpIzRQSOFaO0pU6s44Xt8aTwc","enableSocialMediaInSharePopup":true},"user":{"fkey":"13a86334112524feef461ced01ab29d4","isRegistered":true,"userType":3,"userId":508666,"accountId":239224,"gravatar":"<div class=\"gravatar-wrapper-32\"><img src=\"http://i.stack.imgur.com/nZEUQ.png?s=32&g=1\" alt=\"\"></div>","profileUrl":"http://stackoverflow.com/users/508666/peehaa","notificationsUnviewedCount":0,"inboxUnviewedCount":0,"ab":{"anonymoushero":{"v":"1","g":1}}}});
  55.         StackExchange.using.setCacheBreakers({"js/prettify-full.en.js":"e0bbd4760e83","js/moderator.en.js":"1a411fd265fe","js/full-anon.en.js":"0a48c3f5abce","js/full.en.js":"11c773a111b1","js/wmd.en.js":"bd9234d44a40","js/third-party/jquery.autocomplete.min.js":"e5f01e97f7c3","js/third-party/jquery.autocomplete.min.en.js":"","js/mobile.en.js":"d1d834ef85d2","js/help.en.js":"d3cc74d8a93a","js/tageditor.en.js":"6d51a5f8d7f3","js/tageditornew.en.js":"111b781cf314","js/inline-tag-editing.en.js":"f951bd09dc69","js/revisions.en.js":"33fd38144303","js/review.en.js":"b44cee8b2b0b","js/tagsuggestions.en.js":"e4e7b952fcc7","js/post-validation.en.js":"c275fe37d674","js/explore-qlist.en.js":"73825bd006fc","js/events.en.js":"d92fbd81d9fd"});
  56.         StackExchange.using("gps", function() {
  57.              StackExchange.gps.init(true);
  58.         });
  59.        
  60.     </script>
  61.    
  62. </head>
  63. <body class="question-page new-topbar">
  64.     <noscript><div id="noscript-padding"></div></noscript>
  65.     <div id="notify-container"></div>
  66.     <div id="overlay-header"></div>
  67.     <div id="custom-header"></div>
  68. <div class="topbar">
  69.     <div class="topbar-wrapper">
  70.        
  71.         <div class="js-topbar-dialog-corral">
  72.  
  73. <div class="topbar-dialog siteSwitcher-dialog dno">
  74.     <div class="header">
  75.         <h3><a href="//stackexchange.com/sites">Explore our sites</a></h3>
  76.     </div>
  77.     <div class="modal-content">
  78.         <ul class="current-site">
  79.                 <li>
  80.                         <a href="//stackoverflow.com" class="current-site-link site-link js-site-link">
  81.         <div class="site-icon favicon favicon-stackoverflow" title="Stack Overflow"></div>
  82.         Stack Overflow
  83.     </a>
  84.     <div class="related-links js-related-links">
  85.             <a href="http://chat.stackoverflow.com">chat</a>
  86.                     <a href="http://blog.stackexchange.com">blog</a>
  87.                     <a href="/users/logout">log out</a>
  88.     </div>
  89.  
  90.                 </li>
  91.                 <li class="related-site">
  92.                         <a href="//meta.stackoverflow.com" class="site-link js-site-link">
  93.         <div class="site-icon favicon favicon-stackoverflowmeta" title="Meta Stack Overflow"></div>
  94.         Meta Stack Overflow
  95.     </a>
  96.  
  97.                         <a class="rep-score js-related-links" href="//meta.stackoverflow.com/users/155197">
  98.         4,358
  99.     </a>
  100.  
  101.                 </li>
  102.                             <li class="related-site">
  103.                     <a class="site-link js-site-link" href="//careers.stackoverflow.com">
  104.                         <div class="site-icon favicon favicon-careers" title="Stack Overflow Careers"></div>
  105.                         Stack Overflow Careers 2.0
  106.                     </a>
  107.                 </li>
  108.         </ul>
  109.        
  110.  
  111.  
  112.             <ul>
  113.                     <li>
  114.                             <a href="//webmasters.stackexchange.com" class="site-link js-site-link">
  115.         <div class="site-icon favicon favicon-webmasters" title="Webmasters"></div>
  116.         Webmasters
  117.     </a>
  118.  
  119.                             <a class="rep-score js-related-links" href="//webmasters.stackexchange.com/users/11700">
  120.         901
  121.     </a>
  122.  
  123.                     </li>
  124.                     <li>
  125.                             <a href="//security.stackexchange.com" class="site-link js-site-link">
  126.         <div class="site-icon favicon favicon-security" title="Information Security"></div>
  127.         Information Security
  128.     </a>
  129.  
  130.                             <a class="rep-score js-related-links" href="//security.stackexchange.com/users/2685">
  131.         382
  132.     </a>
  133.  
  134.                     </li>
  135.                     <li>
  136.                             <a href="//codereview.stackexchange.com" class="site-link js-site-link">
  137.         <div class="site-icon favicon favicon-codereview" title="Code Review"></div>
  138.         Code Review
  139.     </a>
  140.  
  141.                             <a class="rep-score js-related-links" href="//codereview.stackexchange.com/users/14812">
  142.         203
  143.     </a>
  144.  
  145.                     </li>
  146.                     <li>
  147.                             <a href="//superuser.com" class="site-link js-site-link">
  148.         <div class="site-icon favicon favicon-superuser" title="Super User"></div>
  149.         Super User
  150.     </a>
  151.  
  152.                             <a class="rep-score js-related-links" href="//superuser.com/users/60642">
  153.         201
  154.     </a>
  155.  
  156.                     </li>
  157.                     <li>
  158.                             <a href="//stackapps.com" class="site-link js-site-link">
  159.         <div class="site-icon favicon favicon-stackapps" title="Stack Apps"></div>
  160.         Stack Apps
  161.     </a>
  162.  
  163.                             <a class="rep-score js-related-links" href="//stackapps.com/users/10013">
  164.         195
  165.     </a>
  166.  
  167.                     </li>
  168.             </ul>
  169.        
  170.             <div class="child-content"></div>
  171.  
  172.     </div>
  173. </div>        </div>
  174.  
  175.         <div class="network-items">
  176.            
  177.             <a href="//stackexchange.com"
  178.               class="topbar-icon icon-site-switcher js-site-switcher-button js-gps-track"
  179.               data-gps-track="site_switcher.show"
  180.               data-child-content-url="/topbar/site-switcher/site-list"
  181.               data-on-class="icon-site-switcher-on"
  182.               title="A list of all 112 Stack Exchange sites">
  183.                 <span class="hidden-text">Stack Exchange</span>
  184.             </a>
  185.            
  186.                 <a href="#"
  187.                   class="topbar-icon icon-inbox js-inbox-button"
  188.                   title="Recent inbox messages">
  189.                     <span class="hidden-text">Inbox</span>
  190.                     <span class="unread-count" style="display:none"></span>
  191.                 </a>
  192.                 <a href="#"
  193.                    class="topbar-icon icon-achievements js-achievements-button "
  194.                    data-unread-class=""
  195.                    title="Recent achievements: reputation, badges, and privileges earned">
  196.                     <span class="hidden-text">Reputation and Badges</span>
  197.                     <span class="unread-count" style="display:none">
  198.                        
  199.                     </span>
  200.                 </a>
  201.         </div>
  202.  
  203.         <div class="topbar-links">
  204.            
  205.                 <a href="/users/508666/peehaa" class="profile-me">
  206.                     <div class="gravatar-wrapper-24" title="PeeHaa"><img src="http://i.stack.imgur.com/nZEUQ.png?s=24&g=1" alt="" class="avatar-me js-avatar-me"></div>
  207.                     <div class="links-container topbar-flair">
  208.  
  209.                         <span class="reputation" title="your reputation: 28,895">
  210.                             28,895
  211.                         </span>
  212. <span title="16 gold badges"><span class="badge1"></span><span class="badgecount">16</span></span><span title="76 silver badges"><span class="badge2"></span><span class="badgecount">76</span></span><span title="141 bronze badges"><span class="badge3"></span><span class="badgecount">141</span></span>                    </div>
  213.                 </a>
  214.                 <div class="links-container">
  215.                     <span class="topbar-menu-links">
  216.                                                     <a href="/review" title="Review queues - help improve the site">
  217.                                 review
  218.                             </a>
  219.  
  220.                             <a href="#" class="icon-help js-help-button" title="Help Center and other resources">
  221.                                 help
  222.                                 <span class="triangle"></span>
  223.                             </a>
  224.                             <div class="topbar-dialog help-dialog js-help-dialog dno">
  225.                                 <div class="modal-content">
  226.                                     <ul>
  227.                                         <li>
  228.                                             <a href="/tour">
  229.                                                 Tour
  230.                                                 <span class="item-summary">
  231.                                                     Start here for a quick overview of the site
  232.                                                 </span>
  233.                                             </a>
  234.                                         </li>
  235.                                         <li>
  236.                                             <a href="/help">
  237.                                                 Help Center
  238.                                                 <span class="item-summary">
  239.                                                     Detailed answers to any questions you might have
  240.                                                 </span>
  241.                                             </a>
  242.                                         </li>
  243.                                             <li>
  244.                                                 <a href="//meta.stackoverflow.com">
  245.                                                     Meta
  246.                                                     <span class="item-summary">
  247.                                                         Discuss the workings and policies of this site
  248.                                                     </span>
  249.                                                 </a>
  250.                                             </li>
  251.                                     </ul>
  252.                                 </div>
  253.                             </div>
  254.                        
  255.                     </span>
  256.                 </div>
  257.  
  258.             <div class="search-container">
  259.                 <form id="search" action="/search" method="get" autocomplete="off">
  260.                     <input name="q" type="text" placeholder="search" value="" tabindex="1" autocomplete="off" maxlength="240" />
  261.                 </form>
  262.             </div>
  263.                
  264.         </div>      
  265.     </div>
  266. </div>
  267. <script>
  268.     StackExchange.ready(function () {
  269.         //topbar.init();
  270.         StackExchange.topbar.init();
  271.     });
  272. </script>    <div class="container">
  273.         <div id="header" >
  274.             <br class="cbt">
  275.             <div id="hlogo">
  276.                 <a href="/">
  277.                     Stack Overflow
  278.                 </a>
  279.             </div>
  280.             <div id="hmenus">
  281.                 <div class="nav mainnavs ">
  282.                     <ul>
  283.                             <li class="youarehere"><a id="nav-questions" href="/questions">Questions</a></li>
  284.                             <li><a id="nav-tags" href="/tags">Tags</a></li>
  285.                             <li><a id="nav-users" href="/users">Users</a></li>
  286.                             <li><a id="nav-badges" href="/help/badges">Badges</a></li>
  287.                             <li><a id="nav-unanswered" href="/unanswered">Unanswered</a></li>
  288.                     </ul>
  289.                 </div>
  290.                 <div class="nav askquestion">
  291.                     <ul>
  292.                         <li>
  293.                             <a id="nav-askquestion"  href="/questions/ask">Ask Question</a>
  294.                         </li>
  295.                     </ul>
  296.                 </div>
  297.             </div>
  298.         </div>
  299.        
  300.  
  301.  
  302.  
  303.         <div id="content">
  304.            
  305.  
  306. <div itemscope itemtype="http://schema.org/Article">
  307.     <link itemprop="image" href="//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">
  308.             <div id="question-header">
  309.             <h1 itemprop="name"><a href="/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices" class="question-hyperlink">HTML5 Canvas Performance and Optimization Tips, Tricks and Coding Best Practices</a></h1>
  310.         </div>
  311.             <div id="mainbar">
  312.  
  313.            
  314.  
  315. <div class="question deleted-answer" data-questionid="8205828"  id="question">
  316.    
  317.         <input type="hidden" id="8205828-only-allow-inform-moderator-flagging" value="true" />
  318.         <table>
  319.         <tr>
  320.             <td class="votecell">
  321.                
  322.  
  323. <div class="vote">
  324.     <input type="hidden" name="_id_" value="8205828">
  325.     <a class="vote-up-off" title="This question shows research effort; it is useful and clear (click again to undo)">up vote</a>
  326.     <span class="vote-count-post ">15</span>
  327.     <a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)">down vote</a>
  328.    
  329.     <a class="star-off" href="#" title="This is a favorite question (click again to undo)">favorite</a>
  330.     <div class="favoritecount"><b>14</b></div>  
  331.  
  332. </div>
  333.  
  334.             </td>
  335.            
  336. <td class="postcell">
  337. <div>
  338.     <div class="post-text" itemprop="description">
  339.  
  340.         <h1>DO YOU KNOW SOME MORE BEST PRACTICES FOR CANVAS??</h1>
  341.  
  342. <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>
  343.  
  344. <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 "best practices" 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>
  345.  
  346. <p><strong>There's so many things that people need to know about, and still so much to learn about too.</strong> </p>
  347.  
  348. <hr>
  349.  
  350. <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>
  351.  
  352. <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>
  353.  
  354. <h1>1. Indent your code</h1>
  355.  
  356. <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>
  357.  
  358. <p>For example:</p>
  359.  
  360. <pre><code>...
  361. // Try to tell me this doesn't make sense to do
  362. ctx.fillStyle = 'red';
  363. ctx.fill();
  364. ctx.save();
  365.     if (thing &lt; 3) {
  366.         // indenting
  367.         ctx.beginPath();
  368.             ctx.arc(2, 6, 11, 0, Math.PI*2, true);
  369.         ctx.closePath();
  370.         ctx.beginPath();
  371.             ctx.moveTo(20, 40);
  372.             ctx.lineTo(10, 200);
  373.             ctx.moveTo(20, 40);
  374.             ctx.lineTo(100, 40);
  375.         ctx.closePath();
  376.         ctx.save();
  377.             ctx.fillStyle = 'blue'
  378.             ctx.fill();
  379.         ctx.restore();
  380.     } else {
  381.         // no indenting
  382.         ctx.drawImage(img, 0, 0, 200, 200);
  383.         ctx.save();
  384.         ctx.shadowBlur();
  385.         ctx.beginPath();
  386.         ctx.arc(2, 60, 10, 0, Math.PI*2, false);
  387.         ctx.closePath();
  388.         ctx.fillStyle 'green';
  389.         ctx.fill();
  390.         ctx.restore();
  391.     }
  392. ctx.restore();
  393. ctx.drawRect();
  394. ctx.fill();
  395. ...
  396. </code></pre>
  397.  
  398. <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>
  399.  
  400. <h1>Use requestAnimationFrame instead of setInterval / setTimeout</h1>
  401.  
  402. <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>
  403.  
  404. <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="nofollow">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="nofollow">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>
  405.  
  406. <h2>ACTUALLY</h2>
  407.  
  408. <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="nofollow">NEW and improved shim</a> called requestInterval and requestTimeout, which he explains what issues exist when using requestAnimFrame.
  409. You can view the <a href="https://gist.github.com/1002116#file_request_interval.js" rel="nofollow">gist of the script</a>.</p>
  410.  
  411. <h2>ACTUALLY x2</h2>
  412.  
  413. <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="nofollow">update to the requestAnimFrame() polyfill</a>, one which will probably remain the one to use to cover all vendors. </p>
  414.  
  415. <h1>Use more than one canvas</h1>
  416.  
  417. <p>A technique for animation-heavy games which <a href="https://twitter.com/nicolahibbert" rel="nofollow">@nicolahibbert</a> wrote about in a <a href="http://nicolahibbert.com/optimising-html5-canvas-games/" rel="nofollow">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 "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."</p>
  418.  
  419. <h2>Render Elements Off-screen</h2>
  420.  
  421. <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="nofollow">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>
  422.  
  423. <pre><code>var tmpCanvas = document.createElement('canvas'),
  424.     tmpCtx = tmpCanvas.getContext('2d'),
  425.     img = document.createElement('img');
  426.  
  427. img.onload = function() {
  428.     tmpCtx.drawImage(thumbImg, 0, 0, 200, 200);
  429. };
  430. img.src = '/some/image/source.png';
  431. </code></pre>
  432.  
  433. <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>
  434.  
  435. <h3>Other tips, tricks and resources</h3>
  436.  
  437. <ul>
  438. <li><strong><a href="http://philip.html5.org/tests/canvas/suite/tests/" rel="nofollow">Canvas test cases</a></strong></li>
  439. <li><strong><a href="http://kangax.github.com/jstests/" rel="nofollow">Some more canvas and JS tests</a></strong></li>
  440. <li><strong><a href="http://www.html5rocks.com/en/tutorials/canvas/performance/" rel="nofollow">HTML5Rocks performance Improving</a></strong></li>
  441. <li>**<a href="http://blog.digitalbackcountry.com/2012/05/using-requestanimationframe-to-optimize-dragging-events/" rel="nofollow">requestAnimFrame to Optimize Dragging Events</a></li>
  442. </ul>
  443.  
  444. <h3>Canvas has a back-reference</h3>
  445.  
  446. <p>The 2d context has a back reference to it's associated DOM element:</p>
  447.  
  448. <pre><code>var ctx = doc.getElementById('canvas').getContext('2d');
  449. console.log(ctx.canvas);    // HTMLCanvasElement
  450. </code></pre>
  451.  
  452. <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="nofollow">Front-end Code Standards and Best Practices</a>. I'd love to get as much feedback on this as I can.</p>
  453.  
  454.     </div>
  455.     <div class="post-taglist">
  456.         <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged &#39;javascript&#39;" rel="tag">javascript</a> <a href="/questions/tagged/performance" class="post-tag" title="show questions tagged &#39;performance&#39;" rel="tag">performance</a> <a href="/questions/tagged/optimization" class="post-tag" title="show questions tagged &#39;optimization&#39;" rel="tag">optimization</a> <a href="/questions/tagged/canvas" class="post-tag" title="show questions tagged &#39;canvas&#39;" rel="tag">canvas</a>
  457.     </div>
  458.     <table class="fw">
  459.     <tr>
  460.     <td class="vt">
  461. <div class="post-menu"><a href="/q/8205828/508666" title="short permalink to this question" class="short-link" id="link-post-8205828">share</a><span class="lsep">|</span><a href="/posts/8205828/edit" class="edit-post" title="revise and improve this post">edit</a><span class="lsep">|</span><a href="#"
  462.       class="close-question-link"
  463.       title="vote to close this question (when closed, no new answers can be added)"
  464.       data-questionid="8205828"
  465.       data-isclosed="false">close</a><span class="lsep">|</span><a href="#"
  466.           id="delete-post-8205828"
  467.           title="2 more votes are needed to undelete this post"
  468.           class="deleted-post load-tooltip-on-hover"
  469.           data-delete-prompt="Vote to delete this post? (19 votes remaining)"
  470.           data-undelete-prompt="Vote to undelete this post? (23 votes remaining)">undelete (1)</a><span class="lsep">|</span><a href="#"
  471.       class="flag-post-link"
  472.       title="flag this post for serious problems or moderator attention"
  473.       data-postid="8205828">flag</a><span class="lsep">|</span><a id="protect-post-8205828" href="#" title="disallow answers by anonymous and very new low rep users">protect</a></div>        
  474.  
  475. <script type="text/javascript">
  476.     StackExchange.using("inlineTagEditing", function () {
  477.         StackExchange.inlineTagEditing.init();
  478.     });
  479. </script>    </td>
  480.     <td align="right" class="post-signature">
  481. <div class="user-info ">
  482.     <div class="user-action-time">
  483.         <a href="/posts/8205828/revisions" title="show all edits to this post">edited <span title="2012-07-29 20:11:57Z" class="relativetime">Jul 29 '12 at 20:11</span></a>
  484.     </div>
  485.     <div class="user-gravatar32">
  486.        
  487.     </div>
  488.     <div class="user-details">
  489.         <br>
  490.        
  491.     </div>
  492. </div>    </td>
  493.     <td class="post-signature">
  494.         <div class="user-info ">
  495.     <div class="user-action-time">
  496.         asked <span title="2011-11-20 23:56:59Z" class="relativetime">Nov 20 '11 at 23:56</span>
  497.     </div>
  498.     <div class="user-gravatar32">
  499.         <a href="/users/297765/jaredwilli"><div><img src="https://www.gravatar.com/avatar/ca85e937926a84231055f0adbaeac6c3?s=32&d=identicon&r=PG" alt="" width="32" height="32"></div></a>
  500.     </div>
  501.     <div class="user-details">
  502.         <a href="/users/297765/jaredwilli">jaredwilli</a><br>
  503.         <span class="reputation-score" title="reputation score " dir="ltr">1,529</span><span title="10 silver badges"><span class="badge2"></span><span class="badgecount">10</span></span><span title="17 bronze badges"><span class="badge3"></span><span class="badgecount">17</span></span>
  504.     </div>
  505. </div>
  506.     </td>
  507.     </tr>
  508.     </table>
  509. </div>
  510. </td>
  511.         </tr>
  512. <tr>
  513.     <td class="votecell"></td>
  514.     <td>
  515.         <div id="comments-8205828" class="comments dno" data-localized="true">
  516.             <table>
  517.                 <tbody data-remaining-comments-count="0"
  518.                        data-addlink-html="comments disabled on deleted / locked posts"
  519.                        data-addlink-disabled="true">
  520.                         <tr><td></td><td></td></tr>
  521.                 </tbody>
  522.             </table>
  523.         </div>
  524.             <a id="comments-link-8205828"
  525.                class="comments-link disabled-link"
  526.                title="Use comments to ask for more information or suggest improvements. Avoid answering questions in comments."
  527.                 >comments disabled on deleted / locked posts</a>
  528.     </td>
  529. </tr>            </table>    
  530. </div>
  531. <div class="question-status">
  532.         <h2>                    <b>deleted</b> by <a href="/users/1228/will">Will</a> <span title="2012-08-29 13:02:15Z" class="relativetime">Aug 29 '12 at 13:02</span>
  533. </h2>
  534.         <p></p>
  535.     </div>
  536.  
  537.             <div id="answers">
  538.  
  539.                 <a name="tab-top"></a>
  540.                 <div id="answers-header">
  541.                     <div class="subheader answers-subheader">
  542.                         <h2>
  543.                                 4 Answers
  544.                         </h2>
  545.                         <div>
  546.                             <div id="tabs">
  547.         <a href="/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices?answertab=active#tab-top" title="Answers with the latest activity first">active</a>
  548.         <a href="/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices?answertab=oldest#tab-top" title="Answers in the order they were provided">oldest</a>
  549.         <a class="youarehere" href="/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices?answertab=votes#tab-top" title="Answers with the highest score first">votes</a>
  550. </div>
  551.                         </div>
  552.                     </div>    
  553.                 </div>    
  554.  
  555.  
  556. <div class="pager-answers">
  557.        
  558.  
  559.  
  560.  
  561.  
  562.  
  563.     </div>
  564.  
  565.  
  566. <a name="8485927"></a>
  567. <div id="answer-8485927" class="answer deleted-answer" data-answerid="8485927" >
  568.         <input type="hidden" id="8485927-only-allow-inform-moderator-flagging" value="true"/>
  569.     <table>
  570.         <tr>
  571.             <td class="votecell">
  572.                
  573.  
  574. <div class="vote">
  575.     <input type="hidden" name="_id_" value="8485927">
  576.     <a class="vote-up-off" title="This answer is useful (click again to undo)">up vote</a>
  577.     <span class="vote-count-post ">6</span>
  578.     <a class="vote-down-off" title="This answer is not useful (click again to undo)">down vote</a>
  579.    
  580.  
  581.  
  582. </div>
  583.  
  584.             </td>
  585.  
  586.  
  587.  
  588. <td class="answercell">
  589.     <div class="post-text"><h1>Redraw Regions</h1>
  590.  
  591. <p>The best canvas optimization technique for animations is to limit the amount of pixels that get cleared/painted on each frame. The easiest solution to implement is resetting the entire canvas element and drawing everything over again but that is an expensive operation for your browser to process.</p>
  592.  
  593. <p>Reuse as many pixels as possible between frames. What that means is the fewer pixels that need to be processed each frame, the faster your program will run. For example, when erasing pixels with the clearRect(x, y, w, h) method, it is very beneficial to clear and redraw only the pixels that have changed and not the full canvas.</p>
  594.  
  595. <h1>Procedural Sprites</h1>
  596.  
  597. <p>Generating graphics procedurally is often the way to go, but sometimes that's not the most efficient one. If you're drawing simple shapes with solid fills then drawing them procedurally is the best way do so. But if you're drawing more detailed entities with strokes, gradient fills and other performance sensitive make-up you'd be better off using image sprites.</p>
  598.  
  599. <p>It is possible to get away with a mix of both. Draw graphical entities procedurally on the canvas once as your application starts up. After that you can reuse the same sprites by painting copies of them instead of generating the same drop-shadow, gradient and strokes repeatedly.</p>
  600.  
  601. <h1>State Stack &amp; Transformation</h1>
  602.  
  603. <p>The canvas can be manipulated via transformations such as rotation and scaling, resulting in a change to the canvas coordinate system. This is where it's important to know about the state stack for which two methods are available: context.save() (pushes the current state to the stack) and context.restore() (reverts to the previous state). This enables you to apply transformation to a drawing and then restore back to the previous state to make sure the next shape is not affected by any earlier transformation. The states also include properties such as the fill and stroke colors.</p>
  604.  
  605. <h1>Compositing</h1>
  606.  
  607. <p>A very powerful tool at hand when working with canvas is compositing modes which, amongst other things, allow for masking and layering. There's a wide array of available composite modes and they are all set through the canvas context's globalCompositeOperation property. The composite modes are also part of the state stack properties, so you can apply a composite operation, stack the state and apply a different one, and restore back to the state before where you made the first one. This can be especially useful.</p>
  608.  
  609. <h1>Anti-Aliasing</h1>
  610.  
  611. <p>To allow for sub-pixel drawings, all browser implementations of canvas employ anti-aliasing (although this does not seem to be a requirement in the HTML5 spec). Anti-aliasing can be important to keep in mind if you want to draw crisp lines and notice the result looks blurred. This occurs because the browser will interpolate the image as though it was actually between those pixels. It results in a much smoother animation (you can genuinely move at half a pixel per update) but it'll make your images appear fuzzy.</p>
  612.  
  613. <p>To work around this you will need to either round to whole integer values or offset by half a pixel depending on if you're drawing fills or strokes.</p>
  614.  
  615. <h2>Using Whole Numbers for drawImage() x and y positions</h2>
  616.  
  617. <p>If you call drawImage on the Canvas element, it's much faster if you round the x and y position to a whole number. </p>
  618.  
  619. <p><a href="http://jsperf.com/drawimage-whole-pixels">Here's a test case on jsperf</a> showing how much faster using whole numbers is compared to using decimals.</p>
  620.  
  621. <p>So round your x and y position to whole numbers before rendering. </p>
  622.  
  623. <h3>Faster than Math.round()</h3>
  624.  
  625. <p><a href="http://jsperf.com/math-round-vs-hack/3">Another jsperf test shows</a> that Math.round() is not necessarily the fastest method for rounding numbers. Using a bitwise hack actually turns out to be faster than the built in method.</p>
  626.  
  627. <p><a href="http://sebleedelisle.com/2011/02/html5-canvas-sprite-optimisation/">Canvas Sprite Optimization</a></p>
  628.  
  629. <h1>Clearing the Canvas</h1>
  630.  
  631. <p>To clear the entire canvas of any existing pixels context.clearRect(x, y, w, h) is typically used – but there is another option available. Whenever the width/height of the canvas are set, even if they are set to the same value repeatedly, the canvas is reset. This is good to know when working with a dynamically sized canvas as you will notice drawings disappearing.</p>
  632.  
  633. <h1>Computation Distribution</h1>
  634.  
  635. <p>The Chrome Developer Tools profiler is very useful for finding out what your performance bottlenecks are. Depending on your application you may need to refactor some parts of your program to improve the performance and how browsers handle specific parts of your code.</p>
  636.  
  637. <p><a href="http://hakim.se/thoughts/canvas-optimization">Optimization techniques</a></p>
  638. </div>
  639.     <table class="fw">
  640.     <tr>
  641.     <td class="vt">
  642. <div class="post-menu"><a href="/a/8485927/508666" title="short permalink to this answer" class="short-link" id="link-post-8485927">share</a><span class="lsep">|</span><a href="/posts/8485927/edit" class="edit-post" title="revise and improve this post">edit</a><span class="lsep">|</span><a href="#"
  643.           id="delete-post-8485927"
  644.           title="vote to undelete this post"
  645.           class="deleted-post"
  646.           data-delete-prompt="Vote to delete this post? (19 votes remaining)"
  647.           data-undelete-prompt="Vote to undelete this post? (23 votes remaining)">undelete</a><span class="lsep">|</span><a href="#"
  648.       class="flag-post-link"
  649.       title="flag this post for serious problems or moderator attention"
  650.       data-postid="8485927">flag</a></div>                <div class="deleted-answer-info">
  651.                 deleted <span title="2012-08-29 13:02:15Z" class="relativetime">Aug 29 '12 at 13:02</span>
  652.             </div>    </td>
  653.            
  654.  
  655.  
  656.     <td align="right" class="post-signature owner">  
  657.        
  658.  
  659.     <div class="user-info ">
  660.     <div class="user-action-time">
  661.         answered <span title="2011-12-13 07:56:56Z" class="relativetime">Dec 13 '11 at 7:56</span>
  662.     </div>
  663.     <div class="user-gravatar32">
  664.         <a href="/users/297765/jaredwilli"><div><img src="https://www.gravatar.com/avatar/ca85e937926a84231055f0adbaeac6c3?s=32&d=identicon&r=PG" alt="" width="32" height="32"></div></a>
  665.     </div>
  666.     <div class="user-details">
  667.         <a href="/users/297765/jaredwilli">jaredwilli</a><br>
  668.         <span class="reputation-score" title="reputation score " dir="ltr">1,529</span><span title="10 silver badges"><span class="badge2"></span><span class="badgecount">10</span></span><span title="17 bronze badges"><span class="badge3"></span><span class="badgecount">17</span></span>
  669.     </div>
  670. </div>
  671.     </td>
  672.     </tr>
  673.     </table>
  674. </td>        </tr>
  675.  
  676. <tr>
  677.     <td class="votecell"></td>
  678.     <td>
  679.         <div id="comments-8485927" class="comments dno" data-localized="true">
  680.             <table>
  681.                 <tbody data-remaining-comments-count="0"
  682.                        data-addlink-html="comments disabled on deleted / locked posts"
  683.                        data-addlink-disabled="true">
  684.                         <tr><td></td><td></td></tr>
  685.                 </tbody>
  686.             </table>
  687.         </div>
  688.             <a id="comments-link-8485927"
  689.                class="comments-link disabled-link"
  690.                title="Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”."
  691.                 >comments disabled on deleted / locked posts</a>
  692.     </td>
  693. </tr>
  694.     </table>
  695. </div>
  696.  
  697.  
  698. <a name="8431202"></a>
  699. <div id="answer-8431202" class="answer deleted-answer" data-answerid="8431202" >
  700.         <input type="hidden" id="8431202-only-allow-inform-moderator-flagging" value="true"/>
  701.     <table>
  702.         <tr>
  703.             <td class="votecell">
  704.                
  705.  
  706. <div class="vote">
  707.     <input type="hidden" name="_id_" value="8431202">
  708.     <a class="vote-up-off" title="This answer is useful (click again to undo)">up vote</a>
  709.     <span class="vote-count-post ">1</span>
  710.     <a class="vote-down-off" title="This answer is not useful (click again to undo)">down vote</a>
  711.    
  712.  
  713.  
  714. </div>
  715.  
  716.             </td>
  717.  
  718.  
  719.  
  720. <td class="answercell">
  721.     <div class="post-text"><p>Here are my tips</p>
  722.  
  723. <p>1) Use clearRect to clear the canvas instead of canvas.width=canvas.width, because later resets the canvas states</p>
  724.  
  725. <p>2) If you are using mouse events on the canvas use following function, its is reliable and works in most of the cases.</p>
  726.  
  727. <pre><code>/**  returns the xy point where the mouse event was occured.
  728.  @param ev The event object.
  729. */
  730. function getXY(ev){
  731.    return getMousePosition(ev, ev.srcElement || ev.originalTarget);
  732. }
  733.  
  734.  /**  returns the top-left point of the element
  735.        @param elem The element
  736.    */
  737. function getElementPos(elem){
  738.    var obj = elem;
  739.    var top = 0;
  740.    var left = 0;
  741.     while (obj &amp;&amp; obj.tagName != "BODY") {
  742.       top += obj.offsetTop-obj.scrollTop;
  743.       left += obj.offsetLeft -obj.scrollLeft ;
  744.       obj = obj.offsetParent;
  745.      }
  746.   return {
  747.     top: top,
  748.     left: left
  749.     };
  750. };
  751.  
  752. /**  returns the xy point where the mouse event was occured inside an element.
  753. @param ev The event object.
  754.  @param elem The element
  755. */
  756. function getMousePosition(evt, elem){
  757. var pageX, pageY;
  758. if(typeof(window.pageYOffset)=='number') {
  759.     pageX=window.pageXOffset;
  760.     pageY=window.pageYOffset;
  761. }else{
  762.     pageX=document.documentElement.scrollLeft;
  763.     pageY=document.documentElement.scrollTop;
  764. }
  765. var mouseX = evt.clientX - getElementPos(elem).left + pageX;
  766. var mouseY = evt.clientY - getElementPos(elem).top + pageY;
  767. return {
  768.     x: mouseX,
  769.     y: mouseY
  770. };
  771. };
  772. </code></pre>
  773.  
  774. <p>3) Use ExplorerCanvas if you want to support IE7</p>
  775.  
  776. <p>4) Instead of clearing the whole canvas clear only the part which is needed to be cleaned. Its good for performance.</p>
  777. </div>
  778.     <table class="fw">
  779.     <tr>
  780.     <td class="vt">
  781. <div class="post-menu"><a href="/a/8431202/508666" title="short permalink to this answer" class="short-link" id="link-post-8431202">share</a><span class="lsep">|</span><a href="/posts/8431202/edit" class="edit-post" title="revise and improve this post">edit</a><span class="lsep">|</span><a href="#"
  782.           id="delete-post-8431202"
  783.           title="vote to undelete this post"
  784.           class="deleted-post"
  785.           data-delete-prompt="Vote to delete this post? (19 votes remaining)"
  786.           data-undelete-prompt="Vote to undelete this post? (23 votes remaining)">undelete</a><span class="lsep">|</span><a href="#"
  787.       class="flag-post-link"
  788.       title="flag this post for serious problems or moderator attention"
  789.       data-postid="8431202">flag</a></div>                <div class="deleted-answer-info">
  790.                 deleted <span title="2012-08-29 13:02:15Z" class="relativetime">Aug 29 '12 at 13:02</span>
  791.             </div>    </td>
  792.     <td align="right" class="post-signature">
  793. <div class="user-info ">
  794.     <div class="user-action-time">
  795.         <a href="/posts/8431202/revisions" title="show all edits to this post">edited <span title="2011-12-10 07:35:32Z" class="relativetime">Dec 10 '11 at 7:35</span></a>
  796.     </div>
  797.     <div class="user-gravatar32">
  798.        
  799.     </div>
  800.     <div class="user-details">
  801.         <br>
  802.        
  803.     </div>
  804. </div>    </td>
  805.            
  806.  
  807.  
  808.     <td align="right" class="post-signature">  
  809.        
  810.  
  811.     <div class="user-info ">
  812.     <div class="user-action-time">
  813.         answered <span title="2011-12-08 12:47:17Z" class="relativetime">Dec 8 '11 at 12:47</span>
  814.     </div>
  815.     <div class="user-gravatar32">
  816.         <a href="/users/845859/shamaila-tahir"><div><img src="https://www.gravatar.com/avatar/aeaf766bb980ef5811a3ac43e88e188b?s=32&d=identicon&r=PG" alt="" width="32" height="32"></div></a>
  817.     </div>
  818.     <div class="user-details">
  819.         <a href="/users/845859/shamaila-tahir">Shamaila Tahir</a><br>
  820.         <span class="reputation-score" title="reputation score " dir="ltr">668</span><span title="5 silver badges"><span class="badge2"></span><span class="badgecount">5</span></span><span title="8 bronze badges"><span class="badge3"></span><span class="badgecount">8</span></span>
  821.     </div>
  822. </div>
  823.     </td>
  824.     </tr>
  825.     </table>
  826. </td>        </tr>
  827.  
  828. <tr>
  829.     <td class="votecell"></td>
  830.     <td>
  831.         <div id="comments-8431202" class="comments" data-localized="true">
  832.             <table>
  833.                 <tbody data-remaining-comments-count="0"
  834.                        data-addlink-html="comments disabled on deleted / locked posts"
  835.                        data-addlink-disabled="true">
  836.  
  837.     <tr id="comment-10441130" class="comment">
  838.         <td class="comment-actions">
  839.             <table>
  840.                 <tbody>
  841.                     <tr>
  842.                         <td class="comment-score">
  843.                            
  844.                         </td>
  845.                         <td>
  846.                                     <a class="comment-up comment-up-off" title="this comment adds something useful to the post">upvote</a>
  847.                         </td>
  848.                     </tr>
  849.                         <tr>
  850.                             <td>&nbsp;</td>
  851.                             <td>
  852.                                     <a class="comment-flag" title="flag this comment as unconstructive, offensive, or spam">flag</a>
  853.                             </td>
  854.                         </tr>
  855.                 </tbody>
  856.             </table>  
  857.         </td>
  858.         <td class="comment-text">
  859.             <div style="display: block;" class="comment-body">
  860.     <span class="comment-copy">Excanvas is a good library for supporting IE, but also another good one is Flashcanvas. I&#39;ve used both, the choice should depend on your needs for a project.</span>
  861.     &ndash;&nbsp;
  862.         <a href="/users/297765/jaredwilli"
  863.            title="1529 reputation"
  864.            class="comment-user owner">jaredwilli</a>
  865.     <span class="comment-date" dir="ltr"><span title="2011-12-09 14:53:33Z" class="relativetime-clean">Dec 9 '11 at 14:53</span></span>
  866.                 </div>
  867.  
  868.         </td>
  869.     </tr>
  870.     <tr id="comment-13120061" class="comment">
  871.         <td class="comment-actions">
  872.             <table>
  873.                 <tbody>
  874.                     <tr>
  875.                         <td class="comment-score">
  876.                            
  877.                         </td>
  878.                         <td>
  879.                                     <a class="comment-up comment-up-off" title="this comment adds something useful to the post">upvote</a>
  880.                         </td>
  881.                     </tr>
  882.                         <tr>
  883.                             <td>&nbsp;</td>
  884.                             <td>
  885.                                     <a class="comment-flag" title="flag this comment as unconstructive, offensive, or spam">flag</a>
  886.                             </td>
  887.                         </tr>
  888.                 </tbody>
  889.             </table>  
  890.         </td>
  891.         <td class="comment-text">
  892.             <div style="display: block;" class="comment-body">
  893.     <span class="comment-copy">I have noticed that Flashcanvas has better support of more things in Canvas, but one thing that I did run into is it&#39;s lack of support for doing things off screen in temporary canvases, and then using drawImage() to draw the temporary canvases into the main context. It is not able to do it unless those canvases are not off-screen.
  894. FxCanvas claims to have support for this, but I was not able to get it to work in the time period I had to try and get it working before a launch</span>
  895.     &ndash;&nbsp;
  896.         <a href="/users/297765/jaredwilli"
  897.            title="1529 reputation"
  898.            class="comment-user owner">jaredwilli</a>
  899.     <span class="comment-date" dir="ltr"><span title="2012-04-18 17:45:56Z" class="relativetime-clean">Apr 18 '12 at 17:45</span></span>
  900.                 </div>
  901.  
  902.         </td>
  903.     </tr>
  904.                 </tbody>
  905.             </table>
  906.         </div>
  907.             <a id="comments-link-8431202"
  908.                class="comments-link disabled-link"
  909.                title="Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”."
  910.                 >comments disabled on deleted / locked posts</a>
  911.     </td>
  912. </tr>
  913.     </table>
  914. </div>
  915.  
  916.  
  917. <a name="10382793"></a>
  918. <div id="answer-10382793" class="answer deleted-answer" data-answerid="10382793" >
  919.         <input type="hidden" id="10382793-only-allow-inform-moderator-flagging" value="true"/>
  920.     <table>
  921.         <tr>
  922.             <td class="votecell">
  923.                
  924.  
  925. <div class="vote">
  926.     <input type="hidden" name="_id_" value="10382793">
  927.     <a class="vote-up-off" title="This answer is useful (click again to undo)">up vote</a>
  928.     <span class="vote-count-post ">1</span>
  929.     <a class="vote-down-off" title="This answer is not useful (click again to undo)">down vote</a>
  930.    
  931.  
  932.  
  933. </div>
  934.  
  935.             </td>
  936.  
  937.  
  938.  
  939. <td class="answercell">
  940.     <div class="post-text"><p>After having worked on a <a href="http://apps.facebook.com/samsunggenomeproject/" rel="nofollow">recently launched Facebook app that uses Canvas</a> and users Facebook profile information (the amount of data it must accommodate is massive for some) to match you and friends of yours also using the app, to Olympic athletes like a 6 degrees of separation type of thing, there's quite a lot I have learned in my extensive efforts to do everything I could possibly try for increasing performance within the app.</p>
  941.  
  942. <p>I literally spent months, and days at a time just working to re-factor the code which I knew already so well, and believed it to be the most optimal way to do things.</p>
  943.  
  944. <h2>Use DOM Elements Whenever Possible</h2>
  945.  
  946. <p>The fact is, browsers are still just not ready to handle more intensive running applications in Canvas, especially if you're required to develop the app with support for IE 8. There are sometimes cases where the DOM is faster than the current implementation of the Canvas API at the time of writing this. <em>At least I've found it to be while working on a massively complex single page animating html5 and canvas application for Samsung.</em></p>
  947.  
  948. <p>We were able to do quite well at improving the performance of things while still using Canvas to do some complex work to crop images into circles, which would've probably been ok to stick with how we were doing it.</p>
  949.  
  950. <p>Days before the launch, we decided to try a different technique, and rather than create temporary canvases off-screen which were placed on the visible canvas once cropped into circles etc.., we just appended Image DOM elements on the Canvas, using the x and y coordinates that we had been using for placing the temp canvases before. </p>
  951.  
  952. <p>For cropping the images into circles, well that was simple, we just used the CSS3 border-radius property to do it which was far less work than the complex series of state changes and while ingenious and creative yet over-use of the .clip() method. </p>
  953.  
  954. <p>Once they are placed in the DOM, the animation of images the occurs, and the DOM nodes for each image are animated as separate entities of the Canvas. Ones that we can have full control over the styling off easily through CSS.</p>
  955.  
  956. <p>This technique is similar to another method for doing this type of work that is quite good to know as well, which involves layering Canvases on top of each other, rather than draw them to one context.</p>
  957. </div>
  958.     <table class="fw">
  959.     <tr>
  960.     <td class="vt">
  961. <div class="post-menu"><a href="/a/10382793/508666" title="short permalink to this answer" class="short-link" id="link-post-10382793">share</a><span class="lsep">|</span><a href="/posts/10382793/edit" class="edit-post" title="revise and improve this post">edit</a><span class="lsep">|</span><a href="#"
  962.           id="delete-post-10382793"
  963.           title="vote to undelete this post"
  964.           class="deleted-post"
  965.           data-delete-prompt="Vote to delete this post? (19 votes remaining)"
  966.           data-undelete-prompt="Vote to undelete this post? (23 votes remaining)">undelete</a><span class="lsep">|</span><a href="#"
  967.       class="flag-post-link"
  968.       title="flag this post for serious problems or moderator attention"
  969.       data-postid="10382793">flag</a></div>                <div class="deleted-answer-info">
  970.                 deleted <span title="2012-08-29 13:02:15Z" class="relativetime">Aug 29 '12 at 13:02</span>
  971.             </div>    </td>
  972.     <td align="right" class="post-signature">
  973. <div class="user-info ">
  974.     <div class="user-action-time">
  975.         <a href="/posts/10382793/revisions" title="show all edits to this post">edited <span title="2012-05-14 23:02:01Z" class="relativetime">May 14 '12 at 23:02</span></a>
  976.     </div>
  977.     <div class="user-gravatar32">
  978.        
  979.     </div>
  980.     <div class="user-details">
  981.         <br>
  982.        
  983.     </div>
  984. </div>    </td>
  985.            
  986.  
  987.  
  988.     <td align="right" class="post-signature owner">  
  989.        
  990.  
  991.     <div class="user-info ">
  992.     <div class="user-action-time">
  993.         answered <span title="2012-04-30 11:16:46Z" class="relativetime">Apr 30 '12 at 11:16</span>
  994.     </div>
  995.     <div class="user-gravatar32">
  996.         <a href="/users/297765/jaredwilli"><div><img src="https://www.gravatar.com/avatar/ca85e937926a84231055f0adbaeac6c3?s=32&d=identicon&r=PG" alt="" width="32" height="32"></div></a>
  997.     </div>
  998.     <div class="user-details">
  999.         <a href="/users/297765/jaredwilli">jaredwilli</a><br>
  1000.         <span class="reputation-score" title="reputation score " dir="ltr">1,529</span><span title="10 silver badges"><span class="badge2"></span><span class="badgecount">10</span></span><span title="17 bronze badges"><span class="badge3"></span><span class="badgecount">17</span></span>
  1001.     </div>
  1002. </div>
  1003.     </td>
  1004.     </tr>
  1005.     </table>
  1006. </td>        </tr>
  1007.  
  1008. <tr>
  1009.     <td class="votecell"></td>
  1010.     <td>
  1011.         <div id="comments-10382793" class="comments dno" data-localized="true">
  1012.             <table>
  1013.                 <tbody data-remaining-comments-count="0"
  1014.                        data-addlink-html="comments disabled on deleted / locked posts"
  1015.                        data-addlink-disabled="true">
  1016.                         <tr><td></td><td></td></tr>
  1017.                 </tbody>
  1018.             </table>
  1019.         </div>
  1020.             <a id="comments-link-10382793"
  1021.                class="comments-link disabled-link"
  1022.                title="Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”."
  1023.                 >comments disabled on deleted / locked posts</a>
  1024.     </td>
  1025. </tr>
  1026.     </table>
  1027. </div>
  1028.  
  1029.  
  1030. <a name="10384269"></a>
  1031. <div id="answer-10384269" class="answer deleted-answer" data-answerid="10384269" >
  1032.         <input type="hidden" id="10384269-only-allow-inform-moderator-flagging" value="true"/>
  1033.     <table>
  1034.         <tr>
  1035.             <td class="votecell">
  1036.                
  1037.  
  1038. <div class="vote">
  1039.     <input type="hidden" name="_id_" value="10384269">
  1040.     <a class="vote-up-off" title="This answer is useful (click again to undo)">up vote</a>
  1041.     <span class="vote-count-post ">1</span>
  1042.     <a class="vote-down-off" title="This answer is not useful (click again to undo)">down vote</a>
  1043.    
  1044.  
  1045.  
  1046. </div>
  1047.  
  1048.             </td>
  1049.  
  1050.  
  1051.  
  1052. <td class="answercell">
  1053.     <div class="post-text"><p>Here's some more tips and suggestions I put into a list last night worth sharing.</p>
  1054.  
  1055. <ul>
  1056. <li><p><strong>Don't include jQuery unless you need to do more than just selecting the <code>&lt;canvas&gt;</code>.</strong></p>
  1057.  
  1058. <p>I've managed to get by without it for almost everything I've made in canvas</p></li>
  1059. <li><p><strong><a href="http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29" rel="nofollow">Create abstracted functions</a></strong> and <strong>decouple your code</strong>. Separate functionality from appearance or initial draw state. </p>
  1060.  
  1061. <p>Make common functions reusable as much as possible. Ideally, you should use a module pattern, which you can create a utils object that contains common functions.</p></li>
  1062. <li><p><strong>Use single and double letter variable names when it makes sense</strong> (<em>x, y, z</em>).</p>
  1063.  
  1064. <p>The coordinate system in Canvas adds more single letters that are
  1065. commonly declared as variables. Which can lead to creating multiple
  1066. single/double variables (<em>dX, dY, aX, aY, vX, vY</em>) as part of an element.</p>
  1067.  
  1068. <p>I suggest you type out or abbr. the word (<em>dirX, accelX, velX</em>) or be descriptive, otherwise things could get pretty confusing for you later on, trust me.</p></li>
  1069. <li><p>Create constructor functions which can be invoked as needed for making game elements. You can add custom methods and properties within the constructor, and create any number of you may need and they all will have their own properties and methods.</p>
  1070.  
  1071. <p><strong>Example of a Ball constructor function I made:</strong></p>
  1072.  
  1073. <pre><code>// Ball constructor
  1074. var Ball = function(x, y) {
  1075.     this.x = x;
  1076.     this.y = y;
  1077.  
  1078.     this.radius = 10;
  1079.     this.color = '#fff';
  1080.  
  1081.     // Direction and min, max x,y
  1082.     this.dX = 15;
  1083.     this.dY = -15;
  1084.  
  1085.     this.minX = this.minY = 20 + this.radius;
  1086.     this.maxX = this.radius - (canvasWidth - 20);
  1087.     this.maxY = this.radius + canvasHeight;
  1088.  
  1089.     this.draw = function(ctx) {
  1090.         ctx.beginPath();
  1091.             ctx.arc(this.x, this.y, this.radius, 0, twoPI, true);
  1092.         ctx.closePath();
  1093.         ctx.save();
  1094.             ctx.fillStyle = this.color;
  1095.             ctx.fill();
  1096.         ctx.restore();
  1097.     };
  1098. };
  1099. </code></pre></li>
  1100. </ul>
  1101.  
  1102. <p>Creating the Ball</p>
  1103.  
  1104. <pre><code>ball = new Ball(centerX, canvasHeight - paddle.height - 30);
  1105. ball.draw(ctx);
  1106. </code></pre>
  1107.  
  1108. <ul>
  1109. <li><p>A good base to work with is to create 3 functions:
  1110.     init() - do all the initial work, and setup the base vars and event handlers etc...
  1111.     draw() - called once to begin the game and draws the first frame of the game, including the creation of elements that may be changing or need constructing.
  1112.     update() - called at the end of draw() and within itself via requestAnimFrame. Updates properties of changing elements, only do what you need to do here.</p></li>
  1113. <li><p><strong>Do the least amount of work within the loop, making updates to the changing parts or elements</strong>. Create the game elements do any other UI work outside the animation loop. </p>
  1114.  
  1115. <p>The animation loop is often a recursive function, meaning it calls itself rapidly and repeatedly during the animation to draw each frame.</p>
  1116.  
  1117. <p>If there are many elements being animated at once, you might want to first create the elements using a constructor function if your not already, and then within the constructor make a 'timer' method that has requestAnimFrame/setTimeout using it just how you would normally within any animation loop, but effects this element specifically only.</p>
  1118.  
  1119. <p><strong>You could make each game element have it's own timer, draw, and animate methods</strong> in the constructor. </p>
  1120.  
  1121. <p>Doing this gives you full separation of control for each element and one big animation loop will not be necessary at all since the loop is broken up into each element and you start/stop at will.</p></li>
  1122. </ul>
  1123.  
  1124. <p>Or another option:</p>
  1125.  
  1126. <ul>
  1127. <li><strong>Create a Timer() constructor function</strong> which you can use and give each animating element individually, thereby minimizing work load within animation loops</li>
  1128. </ul>
  1129. </div>
  1130.     <table class="fw">
  1131.     <tr>
  1132.     <td class="vt">
  1133. <div class="post-menu"><a href="/a/10384269/508666" title="short permalink to this answer" class="short-link" id="link-post-10384269">share</a><span class="lsep">|</span><a href="/posts/10384269/edit" class="edit-post" title="revise and improve this post">edit</a><span class="lsep">|</span><a href="#"
  1134.           id="delete-post-10384269"
  1135.           title="vote to undelete this post"
  1136.           class="deleted-post"
  1137.           data-delete-prompt="Vote to delete this post? (19 votes remaining)"
  1138.           data-undelete-prompt="Vote to undelete this post? (23 votes remaining)">undelete</a><span class="lsep">|</span><a href="#"
  1139.       class="flag-post-link"
  1140.       title="flag this post for serious problems or moderator attention"
  1141.       data-postid="10384269">flag</a></div>                <div class="deleted-answer-info">
  1142.                 deleted <span title="2012-08-29 13:02:15Z" class="relativetime">Aug 29 '12 at 13:02</span>
  1143.             </div>    </td>
  1144.            
  1145.  
  1146.  
  1147.     <td align="right" class="post-signature owner">  
  1148.        
  1149.  
  1150.     <div class="user-info ">
  1151.     <div class="user-action-time">
  1152.         answered <span title="2012-04-30 13:10:21Z" class="relativetime">Apr 30 '12 at 13:10</span>
  1153.     </div>
  1154.     <div class="user-gravatar32">
  1155.         <a href="/users/297765/jaredwilli"><div><img src="https://www.gravatar.com/avatar/ca85e937926a84231055f0adbaeac6c3?s=32&d=identicon&r=PG" alt="" width="32" height="32"></div></a>
  1156.     </div>
  1157.     <div class="user-details">
  1158.         <a href="/users/297765/jaredwilli">jaredwilli</a><br>
  1159.         <span class="reputation-score" title="reputation score " dir="ltr">1,529</span><span title="10 silver badges"><span class="badge2"></span><span class="badgecount">10</span></span><span title="17 bronze badges"><span class="badge3"></span><span class="badgecount">17</span></span>
  1160.     </div>
  1161. </div>
  1162.     </td>
  1163.     </tr>
  1164.     </table>
  1165. </td>        </tr>
  1166.  
  1167. <tr>
  1168.     <td class="votecell"></td>
  1169.     <td>
  1170.         <div id="comments-10384269" class="comments" data-localized="true">
  1171.             <table>
  1172.                 <tbody data-remaining-comments-count="0"
  1173.                        data-addlink-html="comments disabled on deleted / locked posts"
  1174.                        data-addlink-disabled="true">
  1175.  
  1176.     <tr id="comment-13564125" class="comment">
  1177.         <td class="comment-actions">
  1178.             <table>
  1179.                 <tbody>
  1180.                     <tr>
  1181.                         <td class="comment-score">
  1182.                            
  1183.                                 <span title="number of &#39;useful comment&#39; votes received"
  1184.                                        class="cool">1</span>  
  1185.                         </td>
  1186.                         <td>
  1187.                                     <a class="comment-up comment-up-off" title="this comment adds something useful to the post">upvote</a>
  1188.                         </td>
  1189.                     </tr>
  1190.                         <tr>
  1191.                             <td>&nbsp;</td>
  1192.                             <td>
  1193.                                     <a class="comment-flag" title="flag this comment as unconstructive, offensive, or spam">flag</a>
  1194.                             </td>
  1195.                         </tr>
  1196.                 </tbody>
  1197.             </table>  
  1198.         </td>
  1199.         <td class="comment-text">
  1200.             <div style="display: block;" class="comment-body">
  1201.     <span class="comment-copy">Can you give some example code of what you stated above - of creating separate animate methods for separate animation objects ?</span>
  1202.     &ndash;&nbsp;
  1203.         <a href="/users/659074/mad-geek"
  1204.            title="1134 reputation"
  1205.            class="comment-user">mad.geek</a>
  1206.     <span class="comment-date" dir="ltr"><span title="2012-05-08 07:07:32Z" class="relativetime-clean">May 8 '12 at 7:07</span></span>
  1207.                 </div>
  1208.  
  1209.         </td>
  1210.     </tr>
  1211.     <tr id="comment-13694787" class="comment">
  1212.         <td class="comment-actions">
  1213.             <table>
  1214.                 <tbody>
  1215.                     <tr>
  1216.                         <td class="comment-score">
  1217.                            
  1218.                         </td>
  1219.                         <td>
  1220.                                     <a class="comment-up comment-up-off" title="this comment adds something useful to the post">upvote</a>
  1221.                         </td>
  1222.                     </tr>
  1223.                         <tr>
  1224.                             <td>&nbsp;</td>
  1225.                             <td>
  1226.                                     <a class="comment-flag" title="flag this comment as unconstructive, offensive, or spam">flag</a>
  1227.                             </td>
  1228.                         </tr>
  1229.                 </tbody>
  1230.             </table>  
  1231.         </td>
  1232.         <td class="comment-text">
  1233.             <div style="display: block;" class="comment-body">
  1234.     <span class="comment-copy">One way I have seen it implemented is by using an animations array to allow for per-animation intervals. This explains how you would do that: <a href="http://www.planetb.ca/2012/03/html5-game-programming-gems-requestanimationframe/" rel="nofollow">planetb.ca/2012/03/&hellip;</a>
  1235.  
  1236. The Adobe Illustrator to Canvas plugin from Visitmix actually has a much more involved and complex implementation of this technique for animating individual objects. You can see a demo of something which uses it is here: <a href="http://visitmix.com/labs/ai2canvas/common/tutorials/part09/export/Part%2009.html" rel="nofollow">visitmix.com/labs/ai2canvas/common/tutorials/part09/export/&hellip;</a></span>
  1237.     &ndash;&nbsp;
  1238.         <a href="/users/297765/jaredwilli"
  1239.            title="1529 reputation"
  1240.            class="comment-user owner">jaredwilli</a>
  1241.     <span class="comment-date" dir="ltr"><span title="2012-05-14 01:04:54Z" class="relativetime-clean">May 14 '12 at 1:04</span></span>
  1242.         <span class="edited-yes" title="this comment was edited 1 time"></span>
  1243.                 </div>
  1244.  
  1245.         </td>
  1246.     </tr>
  1247.     <tr id="comment-13694806" class="comment">
  1248.         <td class="comment-actions">
  1249.             <table>
  1250.                 <tbody>
  1251.                     <tr>
  1252.                         <td class="comment-score">
  1253.                            
  1254.                         </td>
  1255.                         <td>
  1256.                                     <a class="comment-up comment-up-off" title="this comment adds something useful to the post">upvote</a>
  1257.                         </td>
  1258.                     </tr>
  1259.                         <tr>
  1260.                             <td>&nbsp;</td>
  1261.                             <td>
  1262.                                     <a class="comment-flag" title="flag this comment as unconstructive, offensive, or spam">flag</a>
  1263.                             </td>
  1264.                         </tr>
  1265.                 </tbody>
  1266.             </table>  
  1267.         </td>
  1268.         <td class="comment-text">
  1269.             <div style="display: block;" class="comment-body">
  1270.     <span class="comment-copy">If you look into the source code of the visitmix animation you will find the constructor function called Clock, and subsequent prototypes of it which inherit and extend each new clock created for the different objects of the animation.</span>
  1271.     &ndash;&nbsp;
  1272.         <a href="/users/297765/jaredwilli"
  1273.            title="1529 reputation"
  1274.            class="comment-user owner">jaredwilli</a>
  1275.     <span class="comment-date" dir="ltr"><span title="2012-05-14 01:07:19Z" class="relativetime-clean">May 14 '12 at 1:07</span></span>
  1276.                 </div>
  1277.  
  1278.         </td>
  1279.     </tr>
  1280.     <tr id="comment-13694857" class="comment">
  1281.         <td class="comment-actions">
  1282.             <table>
  1283.                 <tbody>
  1284.                     <tr>
  1285.                         <td class="comment-score">
  1286.                            
  1287.                         </td>
  1288.                         <td>
  1289.                                     <a class="comment-up comment-up-off" title="this comment adds something useful to the post">upvote</a>
  1290.                         </td>
  1291.                     </tr>
  1292.                         <tr>
  1293.                             <td>&nbsp;</td>
  1294.                             <td>
  1295.                                     <a class="comment-flag" title="flag this comment as unconstructive, offensive, or spam">flag</a>
  1296.                             </td>
  1297.                         </tr>
  1298.                 </tbody>
  1299.             </table>  
  1300.         </td>
  1301.         <td class="comment-text">
  1302.             <div style="display: block;" class="comment-body">
  1303.     <span class="comment-copy">One other possible technique which I&#39;ve been working on creating involves the use of constructor functions which are used to create the element(s) you need, which you can create a method which controls &#39;this&#39; elements&#39; clock timer for it&#39;s own animation.</span>
  1304.     &ndash;&nbsp;
  1305.         <a href="/users/297765/jaredwilli"
  1306.            title="1529 reputation"
  1307.            class="comment-user owner">jaredwilli</a>
  1308.     <span class="comment-date" dir="ltr"><span title="2012-05-14 01:13:44Z" class="relativetime-clean">May 14 '12 at 1:13</span></span>
  1309.                 </div>
  1310.  
  1311.         </td>
  1312.     </tr>
  1313.                 </tbody>
  1314.             </table>
  1315.         </div>
  1316.             <a id="comments-link-10384269"
  1317.                class="comments-link disabled-link"
  1318.                title="Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”."
  1319.                 >comments disabled on deleted / locked posts</a>
  1320.     </td>
  1321. </tr>
  1322.     </table>
  1323. </div>
  1324. <div class="pager-answers">
  1325.        
  1326.  
  1327.  
  1328.  
  1329.  
  1330.  
  1331.     </div>             
  1332.                     <script type="text/javascript">
  1333.                         StackExchange.using("inlineEditing", function () {
  1334.                             StackExchange.inlineEditing.init();
  1335.                         });
  1336.                     </script>
  1337.  
  1338.  
  1339.                         <h2 class="bottom-notice">
  1340. Not the answer you&#39;re looking for?                          Browse other questions tagged <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged &#39;javascript&#39;" rel="tag">javascript</a> <a href="/questions/tagged/performance" class="post-tag" title="show questions tagged &#39;performance&#39;" rel="tag">performance</a> <a href="/questions/tagged/optimization" class="post-tag" title="show questions tagged &#39;optimization&#39;" rel="tag">optimization</a> <a href="/questions/tagged/canvas" class="post-tag" title="show questions tagged &#39;canvas&#39;" rel="tag">canvas</a>  or <a href="/questions/ask">ask your own question</a>.                      </h2>
  1341.             </div>
  1342.         </div>
  1343.                 <div id="sidebar" class="show-votes">
  1344.                             <div class="module question-stats">
  1345.                     <p class="label-key">tagged</p>
  1346.                     <div class="tagged"><a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged &#39;javascript&#39;" rel="tag">javascript</a>&nbsp;<span class="item-multiplier"><span class="item-multiplier-x">&times;</span>&nbsp;<span class="item-multiplier-count">495836</span></span><br>
  1347. <a href="/questions/tagged/performance" class="post-tag" title="show questions tagged &#39;performance&#39;" rel="tag">performance</a>&nbsp;<span class="item-multiplier"><span class="item-multiplier-x">&times;</span>&nbsp;<span class="item-multiplier-count">37652</span></span><br>
  1348. <a href="/questions/tagged/optimization" class="post-tag" title="show questions tagged &#39;optimization&#39;" rel="tag">optimization</a>&nbsp;<span class="item-multiplier"><span class="item-multiplier-x">&times;</span>&nbsp;<span class="item-multiplier-count">12735</span></span><br>
  1349. <a href="/questions/tagged/canvas" class="post-tag" title="show questions tagged &#39;canvas&#39;" rel="tag">canvas</a>&nbsp;<span class="item-multiplier"><span class="item-multiplier-x">&times;</span>&nbsp;<span class="item-multiplier-count">10810</span></span><br>
  1350. </div>
  1351.                     <table id="qinfo">
  1352.                         <tr>
  1353.                             <td>
  1354.                                 <p class="label-key">asked</p>
  1355.                             </td>
  1356.                             <td style="padding-left: 10px">
  1357.                                 <p class="label-key" title="2011-11-20 23:56:59Z"><b>2 years ago</b></p>
  1358.                             </td>
  1359.                         </tr>
  1360.                         <tr>
  1361.                             <td>
  1362.                                 <p class="label-key">viewed</p>
  1363.                             </td>
  1364.  
  1365.                             <td style="padding-left: 10px">
  1366.                                 <p class="label-key">
  1367.                                     <b>2867 times</b>
  1368.                                 </p>
  1369.                             </td>
  1370.                         </tr>
  1371.                             <tr>
  1372.                                 <td>
  1373.                                     <p class="label-key">active</p>
  1374.                                 </td>
  1375.                                 <td style="padding-left: 10px">
  1376.                                     <p class="label-key"><b><a href="?lastactivity" class="lastactivity-link" title="2012-07-29 20:11:57Z">1 year ago</a></b></p>
  1377.                                 </td>
  1378.                             </tr>
  1379.                     </table>
  1380.                 </div>
  1381.             <div class="module community-bulletin" data-tracker="cb=1">
  1382.     <h4>Community Bulletin</h4>
  1383.     <div class="related">
  1384.  
  1385.             <div class="spacer">
  1386.                 <div class="bulletin-item-type"><a href="http://blog.stackoverflow.com" class="event-date" target="_blank">blog</a></div>
  1387.                 <div class="bulletin-item-content">
  1388.                     <a href="http://blog.stackoverflow.com/2013/12/a-new-top-bar-for-stack-exchange/" class="question-hyperlink" target="_blank">A New Top Bar for Stack Exchange</a>
  1389.                 </div>
  1390.                 <br class="cbt" />
  1391.             </div>
  1392.     </div>
  1393. </div>         
  1394.             <script type="text/javascript">
  1395.                 var ados = ados || {};ados.run = ados.run || [];
  1396.                 ados.run.push(function() { ados_add_placement(22,8277,"adzerk1617541667",17).setZone(45) ; });                    
  1397.             </script>
  1398.             <div class="everyonelovesstackoverflow" id="adzerk1617541667">
  1399.             </div>  
  1400.     <div id="hireme">
  1401.         <script type="text/javascript">
  1402. window.careers_adurl="//careers.stackoverflow.com/gethired/js",window.careers_cssurl="//cdn-careers.sstatic.net/careers/gethired/sidebar.min.css?v=3c55a7a05afd",window.careers_leaderboardcssurl="//cdn-careers.sstatic.net/careers/gethired/ninja.min.css?v=78ccbfa5c59f",window.careers_companycssurl="//cdn-careers.sstatic.net/careers/gethired/company",window.careers_adselector="div.hireme, div#hireme",StackExchange.ready(function(){$.ajax({url:"//cdn-careers.sstatic.net/careers/gethired/loader.min.js?v=de73430809b3",dataType:"script",cache:!0})});        </script>
  1403.     </div>
  1404.              
  1405.    
  1406.             <div class="module sidebar-linked">
  1407.     <h4 id="h-linked">Linked</h4>
  1408.     <div class="linked" data-tracker="lq=1">
  1409. <div class="spacer">
  1410.     <a href="/q/3488441" title="Vote score (upvotes - downvotes)">
  1411.         <div class="answer-votes  default">9</div>
  1412.     </a>
  1413.     <a href="/questions/3488441/html5-canvas-performance-loading-images-vs-drawing" class="question-hyperlink">HTML5 Canvas Performance: Loading Images vs Drawing</a>
  1414. </div><div class="spacer">
  1415.     <a href="/q/11150779" title="Vote score (upvotes - downvotes)">
  1416.         <div class="answer-votes answered-accepted default">2</div>
  1417.     </a>
  1418.     <a href="/questions/11150779/redrawing-html5-canvas-incredibly-slow" class="question-hyperlink">Redrawing HTML5 canvas incredibly slow</a>
  1419. </div><div class="spacer">
  1420.     <a href="/q/2662321" title="Vote score (upvotes - downvotes)">
  1421.         <div class="answer-votes answered-accepted default">4</div>
  1422.     </a>
  1423.     <a href="/questions/2662321/html-5-canvas-performance" class="question-hyperlink">HTML 5 Canvas performance</a>
  1424. </div><div class="spacer">
  1425.     <a href="/q/4209465" title="Vote score (upvotes - downvotes)">
  1426.         <div class="answer-votes answered-accepted default">3</div>
  1427.     </a>
  1428.     <a href="/questions/4209465/javascript-canvas-html5-performance-questions" class="question-hyperlink">javascript canvas html5 performance questions</a>
  1429. </div><div class="spacer">
  1430.     <a href="/q/6986843" title="Vote score (upvotes - downvotes)">
  1431.         <div class="answer-votes  default">1</div>
  1432.     </a>
  1433.     <a href="/questions/6986843/how-to-properly-render-a-html5-canvas-game-with-best-performance-results" class="question-hyperlink">How to properly render a html5 canvas game with best performance results</a>
  1434. </div><div class="spacer">
  1435.     <a href="/q/11047954" title="Vote score (upvotes - downvotes)">
  1436.         <div class="answer-votes  default">2</div>
  1437.     </a>
  1438.     <a href="/questions/11047954/html5-canvas-optimization-for-a-processingjs-visualization" class="question-hyperlink">HTML5 Canvas optimization for a processingjs visualization</a>
  1439. </div>          </div>
  1440. </div>
  1441.  
  1442.                 <div class="module sidebar-related">
  1443.                     <h4 id="h-related">Related</h4>
  1444.                     <div class="related" data-tracker="rq=1">
  1445.                         <div class="spacer">
  1446. <a href="/q/3630594" title="Vote score (upvotes - downvotes)">
  1447.     <div class="answer-votes answered-accepted default">13
  1448.     </div>
  1449. </a><a href="/questions/3630594/html5-canvas-transformation-matrix" class="question-hyperlink">HTML5 Canvas Transformation Matrix</a>
  1450. </div>
  1451. <div class="spacer">
  1452. <a href="/q/3970461" title="Vote score (upvotes - downvotes)">
  1453.     <div class="answer-votes default">4
  1454.     </div>
  1455. </a><a href="/questions/3970461/html-canvas-drawimage-performance-with-another-canvas" class="question-hyperlink">HTML/Canvas - drawImage performance with another canvas</a>
  1456. </div>
  1457. <div class="spacer">
  1458. <a href="/q/5801116" title="Vote score (upvotes - downvotes)">
  1459.     <div class="answer-votes answered-accepted default">9
  1460.     </div>
  1461. </a><a href="/questions/5801116/how-to-use-html5-canvas-clip" class="question-hyperlink">How to use HTML5 &lt;canvas&gt; clip()</a>
  1462. </div>
  1463. <div class="spacer">
  1464. <a href="/q/8506018" title="Vote score (upvotes - downvotes)">
  1465.     <div class="answer-votes answered-accepted default">0
  1466.     </div>
  1467. </a><a href="/questions/8506018/html5-canvas-in-jquery-array-syntax" class="question-hyperlink">html5 canvas in jquery array syntax</a>
  1468. </div>
  1469. <div class="spacer">
  1470. <a href="/q/8578213" title="Vote score (upvotes - downvotes)">
  1471.     <div class="answer-votes default">0
  1472.     </div>
  1473. </a><a href="/questions/8578213/jquery-html5-canvas-change-color-variable" class="question-hyperlink">Jquery html5 canvas change color variable</a>
  1474. </div>
  1475. <div class="spacer">
  1476. <a href="/q/12565850" title="Vote score (upvotes - downvotes)">
  1477.     <div class="answer-votes default">0
  1478.     </div>
  1479. </a><a href="/questions/12565850/how-to-optimize-drawing-a-lot-elements-on-canvas-js" class="question-hyperlink">How to optimize drawing a lot elements on canvas JS?</a>
  1480. </div>
  1481. <div class="spacer">
  1482. <a href="/q/12597696" title="Vote score (upvotes - downvotes)">
  1483.     <div class="answer-votes answered-accepted default">0
  1484.     </div>
  1485. </a><a href="/questions/12597696/how-to-divide-a-circle-into-three-equal-parts-with-html5-canvas" class="question-hyperlink">How to divide a circle into three equal parts with HTML5 canvas?</a>
  1486. </div>
  1487. <div class="spacer">
  1488. <a href="/q/16684127" title="Vote score (upvotes - downvotes)">
  1489.     <div class="answer-votes answered-accepted default">1
  1490.     </div>
  1491. </a><a href="/questions/16684127/understanding-html5-canvas-element" class="question-hyperlink">Understanding HTML5 Canvas Element</a>
  1492. </div>
  1493. <div class="spacer">
  1494. <a href="/q/17001360" title="Vote score (upvotes - downvotes)">
  1495.     <div class="answer-votes answered-accepted default">0
  1496.     </div>
  1497. </a><a href="/questions/17001360/can-i-plot-html5-canvas-x-y-points-programatically-using-jquery-with-external-js" class="question-hyperlink">Can I plot HTML5 Canvas x/y points programatically using jQuery with external JSON data?</a>
  1498. </div>
  1499.  
  1500.                     </div>
  1501.                 </div>
  1502.         </div>
  1503.         <script type="text/javascript">
  1504. StackExchange.ready(function(){$.get('/posts/8205828/ivc/812e');});
  1505. </script>
  1506. <noscript>
  1507.     <div><img src="/posts/8205828/ivc/812e" class="dno" alt="" width="0" height="0"></div>
  1508. </noscript><div style="display:none" id="prettify-lang">default</div></div>
  1509.  
  1510.  
  1511.         </div>
  1512.     </div>
  1513.     <div id="footer" class="categories">
  1514.         <div class="footerwrap">
  1515.             <div id="footer-menu">
  1516.                 <div class="top-footer-links">
  1517.                         <a href="/about">about</a>
  1518.                     <a href="/help">help</a>
  1519.                     <a href="http://blog.stackexchange.com?blb=1">blog</a>
  1520.                         <a href="http://chat.stackoverflow.com">chat</a>
  1521.                     <a href="http://data.stackexchange.com">data</a>
  1522.                     <a href="http://stackexchange.com/legal">legal</a>
  1523.                     <a href="http://stackexchange.com/legal/privacy-policy">privacy policy</a>
  1524.                     <a href="http://stackexchange.com/about/hiring">jobs</a>
  1525.                     <a href="http://engine.adzerk.net/r?e=eyJhdiI6NDE0LCJhdCI6MjAsImNtIjo5NTQsImNoIjoxMTc4LCJjciI6Mjc3NiwiZG0iOjQsImZjIjoyODYyLCJmbCI6Mjc1MSwibnciOjIyLCJydiI6MCwicHIiOjExNSwic3QiOjAsInVyIjoiaHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL2Fib3V0L2NvbnRhY3QiLCJyZSI6MX0&amp;s=hRods5B22XvRBwWIwtIMekcyNF8">advertising info</a>
  1526.  
  1527.                     <a onclick='StackExchange.switchMobile("on", "/questions/8205828/html5-canvas-performance-and-optimization-tips-tricks-and-coding-best-practices")'>mobile</a>
  1528.                     <b><a href="/contact">contact us</a></b>
  1529.                         <b><a href="http://meta.stackoverflow.com">feedback</a></b>
  1530.                    
  1531.                 </div>
  1532.                 <div id="footer-sites">
  1533.                     <table>
  1534.     <tr>
  1535.             <th colspan=3>
  1536.                 Technology
  1537.             </th>
  1538.             <th >
  1539.                 Life / Arts
  1540.             </th>
  1541.             <th >
  1542.                 Culture / Recreation
  1543.             </th>
  1544.             <th >
  1545.                 Science
  1546.             </th>
  1547.             <th >
  1548.                 Other
  1549.             </th>
  1550.     </tr>
  1551.     <tr>
  1552.             <td>
  1553.                 <ol>
  1554.                         <li><a href="http://stackoverflow.com" title="professional and enthusiast programmers">Stack Overflow</a></li>
  1555.                         <li><a href="http://serverfault.com" title="professional system and network administrators">Server Fault</a></li>
  1556.                         <li><a href="http://superuser.com" title="computer enthusiasts and power users">Super User</a></li>
  1557.                         <li><a href="http://webapps.stackexchange.com" title="power users of web applications">Web Applications</a></li>
  1558.                         <li><a href="http://askubuntu.com" title="Ubuntu users and developers">Ask Ubuntu</a></li>
  1559.                         <li><a href="http://webmasters.stackexchange.com" title="pro webmasters">Webmasters</a></li>
  1560.                         <li><a href="http://gamedev.stackexchange.com" title="professional and independent game developers">Game Development</a></li>
  1561.                         <li><a href="http://tex.stackexchange.com" title="users of TeX, LaTeX, ConTeXt, and related typesetting systems">TeX - LaTeX</a></li>
  1562.                             </ol></td><td><ol>
  1563.                         <li><a href="http://programmers.stackexchange.com" title="professional programmers interested in conceptual questions about software development">Programmers</a></li>
  1564.                         <li><a href="http://unix.stackexchange.com" title="users of Linux, FreeBSD and other Un*x-like operating systems.">Unix &amp; Linux</a></li>
  1565.                         <li><a href="http://apple.stackexchange.com" title="power users of Apple hardware and software">Ask Different (Apple)</a></li>
  1566.                         <li><a href="http://wordpress.stackexchange.com" title="WordPress developers and administrators">WordPress Answers</a></li>
  1567.                         <li><a href="http://gis.stackexchange.com" title="cartographers, geographers and GIS professionals">Geographic Information Systems</a></li>
  1568.                         <li><a href="http://electronics.stackexchange.com" title="electronics and electrical engineering professionals, students, and enthusiasts">Electrical Engineering</a></li>
  1569.                         <li><a href="http://android.stackexchange.com" title="enthusiasts and power users of the Android operating system">Android Enthusiasts</a></li>
  1570.                         <li><a href="http://security.stackexchange.com" title="Information security professionals">Information Security</a></li>
  1571.                             </ol></td><td><ol>
  1572.                         <li><a href="http://dba.stackexchange.com" title="database professionals who wish to improve their database skills and learn from others in the community">Database Administrators</a></li>
  1573.                         <li><a href="http://drupal.stackexchange.com" title="Drupal developers and administrators">Drupal Answers</a></li>
  1574.                         <li><a href="http://sharepoint.stackexchange.com" title="SharePoint enthusiasts">SharePoint</a></li>
  1575.                         <li><a href="http://ux.stackexchange.com" title="user experience researchers and experts">User Experience</a></li>
  1576.                         <li><a href="http://mathematica.stackexchange.com" title="users of Mathematica">Mathematica</a></li>
  1577.                    
  1578.                         <li>
  1579.                             <a href="http://stackexchange.com/sites#technology" class="more">
  1580.                                 more (14)
  1581.                             </a>
  1582.                         </li>
  1583.                 </ol>
  1584.             </td>
  1585.             <td>
  1586.                 <ol>
  1587.                         <li><a href="http://photo.stackexchange.com" title="professional, enthusiast and amateur photographers">Photography</a></li>
  1588.                         <li><a href="http://scifi.stackexchange.com" title="science fiction and fantasy enthusiasts">Science Fiction &amp; Fantasy</a></li>
  1589.                         <li><a href="http://cooking.stackexchange.com" title="professional and amateur chefs">Seasoned Advice (cooking)</a></li>
  1590.                         <li><a href="http://diy.stackexchange.com" title="contractors and serious DIYers">Home Improvement</a></li>
  1591.                    
  1592.                         <li>
  1593.                             <a href="http://stackexchange.com/sites#lifearts" class="more">
  1594.                                 more (13)
  1595.                             </a>
  1596.                         </li>
  1597.                 </ol>
  1598.             </td>
  1599.             <td>
  1600.                 <ol>
  1601.                         <li><a href="http://english.stackexchange.com" title="linguists, etymologists, and serious English language enthusiasts">English Language &amp; Usage</a></li>
  1602.                         <li><a href="http://skeptics.stackexchange.com" title="scientific skepticism">Skeptics</a></li>
  1603.                         <li><a href="http://judaism.stackexchange.com" title="those who base their lives on Jewish law and tradition and anyone interested in learning more">Mi Yodeya (Judaism)</a></li>
  1604.                         <li><a href="http://travel.stackexchange.com" title="road warriors and seasoned travelers">Travel</a></li>
  1605.                         <li><a href="http://christianity.stackexchange.com" title="committed Christians, experts in Christianity and those interested in learning more">Christianity</a></li>
  1606.                         <li><a href="http://gaming.stackexchange.com" title="passionate videogamers on all platforms">Arqade (gaming)</a></li>
  1607.                         <li><a href="http://bicycles.stackexchange.com" title="people who build and repair bicycles, people who train cycling, or commute on bicycles">Bicycles</a></li>
  1608.                         <li><a href="http://rpg.stackexchange.com" title="gamemasters and players of tabletop, paper-and-pencil role-playing games">Role-playing Games</a></li>
  1609.                    
  1610.                         <li>
  1611.                             <a href="http://stackexchange.com/sites#culturerecreation" class="more">
  1612.                                 more (21)
  1613.                             </a>
  1614.                         </li>
  1615.                 </ol>
  1616.             </td>
  1617.             <td>
  1618.                 <ol>
  1619.                         <li><a href="http://math.stackexchange.com" title="people studying math at any level and professionals in related fields">Mathematics</a></li>
  1620.                         <li><a href="http://stats.stackexchange.com" title="statisticians, data analysts, data miners and data visualization experts">Cross Validated (stats)</a></li>
  1621.                         <li><a href="http://cstheory.stackexchange.com" title="theoretical computer scientists and researchers in related fields">Theoretical Computer Science</a></li>
  1622.                         <li><a href="http://physics.stackexchange.com" title="active researchers, academics and students of physics">Physics</a></li>
  1623.                         <li><a href="http://mathoverflow.net" title="professional mathematicians">MathOverflow</a></li>
  1624.                    
  1625.                         <li>
  1626.                             <a href="http://stackexchange.com/sites#science" class="more">
  1627.                                 more (7)
  1628.                             </a>
  1629.                         </li>
  1630.                 </ol>
  1631.             </td>
  1632.             <td>
  1633.                 <ol>
  1634.                         <li><a href="http://stackapps.com" title="apps, scripts, and development with the Stack Exchange API">Stack Apps</a></li>
  1635.                         <li><a href="http://meta.stackoverflow.com" title="meta-discussion of the Stack Exchange family of Q&amp;A websites">Meta Stack Overflow</a></li>
  1636.                         <li><a href="http://area51.stackexchange.com" title="proposing new sites in the Stack Exchange network">Area 51</a></li>
  1637.                         <li><a href="http://careers.stackoverflow.com">Stack Overflow Careers</a></li>
  1638.                    
  1639.                 </ol>
  1640.             </td>
  1641.     </tr>
  1642. </table>
  1643.                 </div>
  1644.             </div>
  1645.  
  1646.             <div id="copyright">
  1647.                 site design / logo &#169; 2013 stack exchange inc; user contributions licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/" rel="license">cc-wiki</a>
  1648.  with <a href="http://blog.stackoverflow.com/2009/06/attribution-required/" rel="license">attribution required</a>
  1649.             </div>
  1650.             <div id="footer-flair">
  1651.                 <a href="http://creativecommons.org/licenses/by-sa/3.0/" class="cc-wiki-link"></a>
  1652.             </div>
  1653.             <div id="svnrev">
  1654.                 rev 2013.12.5.1201
  1655.             </div>
  1656.            
  1657.         </div>
  1658.     </div>
  1659.     <noscript>
  1660.         <div id="noscript-warning">Stack Overflow works best with JavaScript enabled<img src="http://pixel.quantserve.com/pixel/p-c1rF4kxgLUzNc.gif" alt="" class="dno"></div>
  1661.     </noscript>
  1662. <script type="text/javascript">var p = "http", d = "static"; if (document.location.protocol == "https:") { p += "s"; d = "engine"; } var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = p + "://" + d + ".adzerk.net/ados.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script>
  1663. <script type="text/javascript">
  1664.     var ados = ados || {};
  1665.     ados.run = ados.run || [];
  1666.     ados.run.push(function () { ados_setKeywords('javascript,performance,optimization,canvas,x-user-registered,x-user-highrep');; ados_load(); });        
  1667. </script>
  1668.  
  1669.     <script type="text/javascript">var _gaq=_gaq||[];_gaq.push(['_setAccount','UA-5620270-1']);
  1670.         _gaq.push(['_setCustomVar', 1, 'tags', '|javascript|performance|optimization|canvas|']);
  1671.         _gaq.push(['_setCustomVar', 2, 'accountid', '239224',2]);
  1672. _gaq.push(['_trackPageview']);
  1673.     var _qevents = _qevents || [];
  1674.     var _comscore = _comscore || [];
  1675.     (function () {
  1676.         var ssl='https:'==document.location.protocol,
  1677.             s=document.getElementsByTagName('script')[0],
  1678.             ga=document.createElement('script');
  1679.         ga.type='text/javascript';
  1680.         ga.async=true;
  1681.         ga.src=(ssl?'https://ssl':'http://www')+'.google-analytics.com/ga.js';
  1682.         s.parentNode.insertBefore(ga,s);
  1683.         var sc=document.createElement('script');
  1684.         sc.type='text/javascript';
  1685.         sc.async=true;
  1686.         sc.src=(ssl?'https://secure':'http://edge')+'.quantserve.com/quant.js';
  1687.         s.parentNode.insertBefore(sc, s);
  1688.        
  1689.         var s = document.createElement("script"), el = document.getElementsByTagName("script")[0]; s.async = true;
  1690.         s.src = (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js";
  1691.         el.parentNode.insertBefore(s, el);
  1692.        
  1693.     })();
  1694.     _comscore.push({ c1: "2", c2: "17440561" });
  1695.     _qevents.push({ qacct: "p-c1rF4kxgLUzNc" });
  1696.     </script>            
  1697. </body>
  1698. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement