text: <!DOCTYPE html>
  <html id="top">
    <head>
      <meta charset="utf-8">
      <title>The Crosswalk Project</title>
      <link rel="shorcut icon" href="/assets/favicon.ico" type="image/x-icon" />
      <link rel="icon" href="/assets/favicon.ico" type="image/x-icon" />
      <script>
        WebFontConfig = {
          custom: {
            families: ['Clear Sans'],
            urls: ['/css/fonts.css']
          },
          google: {
            families: ['Source Code Pro:n4,n6']
          },
          timeout: 2000
        };
      </script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script async defer src="//ajax.googleapis.com/ajax/libs/webfont/1.5.3/webfont.js"></script>
      <link rel="stylesheet" href="/css/main.css">
  
      <meta name="description" content="Enable the most advanced web innovations with the Crosswalk Project web runtime to develop powerful Android and Cordova apps." />
      <meta name="author" content="Crosswalk" />
      <meta name="handheldfriendly" content="true" />
      <meta name="mobileoptimized" content="320" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="cleartype" content="on" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  
      <!-- Facebook -->
      <meta property="og:side_name" content="Crosswalk" />
      <meta property="og:title" content="Crosswalk" />
      <meta property="og:url" content="http://crosswalk-project.org/documentation/tutorials/screens" />
      <meta property="og:description" content="Enable the most advanced web innovations with the Crosswalk Project web runtime to develop powerful Android and Cordova apps." />
      <meta property="og:image" content="/assets/crosswalk-og-banner.jpg" />
  
      <!-- Twitter -->
      <meta name="twitter:card" content="summary" />
      <meta name="twitter:url" content="http://crosswalk-project.org/documentation/tutorials/screens" />
      <meta name="twitter:title" content="Crosswalk" />
      <meta name="twitter:description" content="Enable the most advanced web innovations with the Crosswalk Project web runtime to develop powerful Android and Cordova apps." />
      <meta name="twitter:site" content="@xwalk_project" />
  
      <!-- Relevant original Crosswalk Project JS -->
      <script src="/js/utils.js"></script>
      <script src="/js/xwalk.js"></script>
      <script src="/js/versions.js"></script>
      <script src="/js/demos.js"></script>
      <script src="/js/testimonials.js"></script>
      <script src="/js/tools.js"></script>
      <script src="/js/qualityindicators.js"></script>
      <script src="/js/i18n.js"></script>
      <script src="/js/highlight.pack.js"></script>
      <script>hljs.initHighlightingOnLoad();</script>
      <script language="javascript" type="text/javascript">
        var style = document.createElement('style');
        style.type = "text/css";
        style.id = "antiClickjack";
        style.innerHTML = "body{display:none !important;}";
        if (self === top) {
          var antiClickjack = document.getElementById("antiClickjack");
          antiClickjack.parentNode.removeChild(antiClickjack);
        } else {
          top.location = self.location;
        }
      </script>
  
    </head>
    <body>
      <!-- If curr page named 'index' and less than 2 dirs deep,
           do custom layouts. (home screen, blog, app-mgmt page)
           Else, provide doc header and nav. -->
      
      <div class="container">
        <div class="doc-header">
          
  
  
    <div class="doc-logo-div">
       <a href="/" class="doc-logo-link">
         <img src="/assets/identity/crosswalkproject-logo-horizontal-dark.png" class="doc-logo-img">
       </a>
    </div>
    <div class="doc-nav-div">
      <ul class="doc-nav-list">
        <li class="doc-nav-item">
          <a href="/documentation/getting_started.html" class="doc-nav-link">Documentation</a>
        </li>
        <li class="doc-nav-item">
          <a href="/blog" class="doc-nav-link">Blog</a>
        </li>
        <li class="doc-nav-item hide-on-small">
          <a href="/contribute" class="doc-nav-link">Contribute</a>
        </li>
        <li class="doc-nav-item hide-on-small">
          <a href="https://github.com/crosswalk-project/crosswalk-website/wiki" class="doc-nav-link">Wiki</a>
        </li>
        <li class="doc-nav-item hide-on-small">
          <a href="/documentation/about/faq.html" class="doc-nav-link">FAQ</a>
        </li>
        <li class="doc-nav-item">
  	<span class="i18n-label" id="i18n-label">
  	  <span id="i18n-inner">
  	    <img src="/assets/i18n-globe.png" class="i18n-globe" />
  	    English
  	    <img src="/assets/i18n-arrow.png" class="i18n-arrow"/>
  	  </span>
  	  <div id="i18n-menu" class="i18n-menu i18n-menu-light">
              <a onclick="switchLanguage('English')">English</a>
              <a onclick="switchLanguage('Chinese')">中文版</a>
  	  </div>
  	</span>
        </li>
      </ul>
    </div>
    
  
        </div>
        <br />
        <div class="doc-main">
          <div class="row">
            
            <div id="translation-missing-toaster">
    <p style="padding:10px"> 抱歉，该网页目前还不存在中文版本，请继续浏览其他网页！ </p>
  </div>
  
            
  
  
  
  <nav id="contents" class="article-toc nav-toggleContainer">
    <a href="#contents" id="contents-toggle" class="button button--small button--tertiary nav-toggle">Table of Contents</a>
    <a href="./#contents-toggle" class="button button--small button--tertiary nav-toggle--dummy">Table of Contents</a>
    <ul class="article-list nav-toggleHide">
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/about.html">About</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/getting_started.html">Getting Started</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/crosswalk-app-tools.html">Crosswalk App Tools</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/android.html">Android</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/ios.html">iOS</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/windows.html">Windows</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/linux.html">Linux</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/cordova.html">Cordova</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/tizen.html">Tizen</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/manifest.html">Manifest</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/apis.html">APIs</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/downloads.html">Downloads</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/shared_mode.html">Shared Mode</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/download_mode.html">Download Mode</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/crosswalk_lite.html">Crosswalk Lite</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/tutorials.html">Tutorials</a>
          
              <ul class="article-list">
              
                <li class="article-item ">
                  <a class="article-link" href="/documentation/tutorials/realsense.html">Intel RealSense</a>
                  
                </li>
              
                <li class="article-item ">
                  <a class="article-link" href="/documentation/tutorials/webvr.html">WebVR</a>
                  
                </li>
              
                <li class="article-item ">
                  <a class="article-link" href="/documentation/tutorials/security-api.html">Intel Security APIs</a>
                  
                </li>
              
                <li class="article-item ">
                  <a class="article-link" href="/documentation/tutorials/webrtc.html">WebRTC</a>
                  
                </li>
              
                <li class="article-item ">
                  <a class="article-link" href="/documentation/tutorials/webcl.html">WebCL</a>
                  
                </li>
              
                <li class="article-item  nav-item--active">
                  <a class="article-link" href="/documentation/tutorials/screens.html">Screens</a>
                  
                    <ul class="article-list">
                    
                    </ul>
                  
                </li>
              
                <li class="article-item ">
                  <a class="article-link" href="/documentation/tutorials/webassembly.html">Web Assembly</a>
                  
                </li>
              
              </ul>
            
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/samples.html">Samples</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/community.html">Community</a>
          
          </li>
      
          <li class="article-item ">
          <a class="article-link" href="/documentation/qa.html">Quality Assurance</a>
          
          </li>
      
    </ul>
  
  </nav>
  
  <article class="article article--hasToC">
    <h1>Screen APIs</h1>
  <p>The Crosswalk Project simplifies the difficult task of making an application work well on a small screen, with the same look and feel as a native application.</p>
  <p>Some of the most common screen-related issues on mobile devices are:</p>
  <ul>
  <li>Fitting the application to the &quot;real&quot; screen width and height.</li>
  <li>Locking the screen orientation to the one preferred for the application.</li>
  <li>Showing an application in fullscreen mode with no system toolbars.</li>
  <li>Using different layouts or assets depending on screen size.</li>
  <li>Showing a launch screen while an application is loading.</li>
  </ul>
  <p>A number of solutions for such issues have surfaced over the last few years, either as de facto &quot;standards&quot; (e.g. the <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html#//apple_ref/doc/uid/TP40008193-SW6"><code>&lt;meta name=&quot;viewport&quot;&gt;</code> element</a>), vendor-specific browser extensions (e.g. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Screen.lockOrientation">Mozilla&#39;s implementation of screen.lockOrientation</a>), or application-specific work-arounds in JavaScript and CSS (e.g. <a href="https://github.com/01org/webapps-slider-puzzle/blob/master/app/js/main.js">this rotation hack</a>). Recently, work has started on creating formal standards based on these interim solutions. However, many browsers and web views lag behind these standards.</p>
  <p>By contrast, one major benefit of Crosswalk is that many of these evolving standards are implemented and available for use <em>right now</em>. In this article, I&#39;ll describe how to resolve some of the issues listed above using Crosswalk by optimising a simple side-scrolling HTML5 game for mobile screens.</p>
  <h2>Aside: measuring the screen in HTML5 applications</h2>
  <p>One major complexity when working with HTML5 and CSS is figuring out how CSS pixels and physical pixels on the screen relate to each other. For the purposes of this article, I&#39;ve glossed over these issues, as they can mostly be ignored if you aren&#39;t too concerned about how consistent a game appearson different devices. However, there are other situations where it is important to understand these nuances; for example, if you want your game to look identical on different devices, you will have to pay attention to screen densities.</p>
  <p>To help in these situations, the <a href="/documentation/tutorials/screens/screen_measurements.html">screen measurements page</a> explains the terminology, including units and measurements, which are relevant when dealing with heterogenous screens in detail.</p>
  <p>You may also find it useful to refer to <a href="http://www.html5rocks.com/en/tutorials/canvas/hidpi/">this article</a> about working with the <code>&lt;canvas&gt;</code> element on HiDPI (aka retina) displays.</p>
  <h2>The game</h2>
  <p>The game used in this article is a side-scrolling dodge game set in space. The code is <a href="https://github.com/crosswalk-project/crosswalk-samples">available on github</a>.</p>
  <p>The layout of the game looks like this (shown in a Chrome browser on a Linux desktop machine):</p>
  <p><img src="/assets/space_dodge_game-chrome_linux_desktop.png" alt="space dodge game in Chrome on Linux desktop"></p>
  <p>The container element for the whole game is sized using CSS, and is 750 pixels across by 450 pixels down. It is positioned relative to the top-left of the browser window.</p>
  <p>Inside the container are a <code>&lt;div&gt;</code> for the game screen, consisting of a controls <code>&lt;div&gt;</code> on the left and a <code>&lt;canvas&gt;</code> for the play area on the right; and another <code>&lt;div&gt;</code> for the &quot;game over&quot; screen, which is initially hidden.</p>
  <p>The controls <code>&lt;div&gt;</code> is sized relative to the container, and take up 20% of its width (150px) and 100% of its height (450px). The elements inside the controls area are positioned using the <a href="http://www.w3.org/TR/css-flexbox-1/">CSS flexbox</a>. The CSS flexbox is the first example of a useful feature which is available in Crosswalk, but not in older browsers. It&#39;s very handy for laying out game controls, as you can vertically and horizontally align elements inside a flex element.</p>
  <p><code>&lt;canvas&gt;</code> elements have to have a pixel width and height specified for them (you can&#39;t size them in CSS). For this first version of the game, the <code>&lt;canvas&gt;</code> is sized to 600 pixels across and 450 pixels down. This is then put in the right-hand side of the game screen.</p>
  <p>The sprites for the ship and the asteroids are loaded from PNG graphic files and drawn to the canvas. If you are unfamiliar with how to do this, see <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial">this <code>&lt;canvas&gt;</code> tutorial</a>.</p>
  <p>The gameplay is nothing special, but is just there to demonstrate the effect of applying various screen-related techniques to the game. The game is touch-enabled, though, so it will work on a touchscreen devices like phones.</p>
  <h3>Notes on the game layout</h3>
  <p>The layout elements in the HTML file <code>index.html</code>:</p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;meta charset=&quot;utf-8&quot;&gt;
      &lt;title&gt;space dodge game&lt;/title&gt;
      &lt;link rel=&quot;stylesheet&quot; href=&quot;base.css&quot;&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
  
      &lt;div id=&quot;container&quot;&gt;
  
        &lt;div id=&quot;game-screen&quot;&gt;
          &lt;div id=&quot;controls&quot; class=&quot;vbox&quot;&gt;
            &lt;p id=&quot;score&quot;&gt;Score&lt;br&gt;&lt;span id=&quot;score-display&quot;&gt;&lt;/span&gt;&lt;/p&gt;
            &lt;img id=&quot;control-up&quot; src=&quot;control-up.png&quot;&gt;
            &lt;img id=&quot;control-down&quot; src=&quot;control-down.png&quot;&gt;
          &lt;/div&gt;
          &lt;canvas id=&quot;play-area&quot; width=&quot;600&quot; height=&quot;450&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;
  
        &lt;div id=&quot;finish-screen&quot; class=&quot;vbox&quot; data-visible=&quot;false&quot;&gt;
          &lt;p id=&quot;final-score&quot;&gt;&lt;/p&gt;
          &lt;button id=&quot;restart&quot;&gt;Restart&lt;/button&gt;
        &lt;/div&gt;
  
      &lt;/div&gt;
  
      &lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;
  
    &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  <p>The CSS stylesheet:</p>
  <pre><code>* {
    user-select: none;
    -webkit-user-select: none;
    user-drag: none;
    -webkit-user-drag: none;
  }
  
  body {
    margin: 0;
  }
  
  #container {
    position: relative;
    top: 0;
    left: 0;
    width: 750px;
    height: 450px;
  }
  
  #game-screen, #finish-screen {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #11F;
  }
  
  #finish-screen {
    z-index: 100;
  }
  
  #play-area {
    float: right;
    width: 80%;
  }
  
  #controls {
    height: 100%;
    width: 20%;
    padding: 5%;
    text-align: center;
    box-sizing: border-box;
    float: left;
  }
  
  .vbox {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  
  p, button {
    font-family: sans-serif;
    font-size: 1.5em;
  }
  
  #control-up, #control-down {
    margin: 1em 0;
  }
  
  #finish-screen &gt; * {
    text-align: center;
  }
  
  #score, #final-score {
    color: white;
  }
  
  [data-visible=&quot;false&quot;] {
    display: none !important;
  }</code></pre>
  <p>Some remarks about the code:</p>
  <ul>
  <li><p>The margins are removed from the <code>body</code> element with:</p>
  <pre><code>body {
    margin: 0;
  }</code></pre>
  <p>This makes it easier to do accurate positioning and sizing of elements inside the body.</p>
  </li>
  <li><p>The outer element with ID <code>container</code> contains all of the other game elements. Its size is sets in CSS, which constrains the size of the whole game.</p>
  </li>
  <li><p>There are two separate &quot;screens&quot; inside the container (elements with the IDs <code>game-screen</code> and <code>finish-screen</code>). <code>finish-screen</code> is hidden initially, but is placed on top of <code>game-screen</code> by setting a <code>z-index</code> of 100. When the game ends, <code>finish-screen</code> is shown, which obscures the <code>game-screen</code> element underneath it.</p>
  </li>
  <li><p><code>&lt;canvas&gt;</code> elements must have their height and width attributes set to define the size of the canvas in pixels. This can&#39;t be done in CSS. In the code above, the height and width are fixed; but they can be set dynamically based on the size of the screen (see later).</p>
  </li>
  <li><p>The container has <code>position: relative</code> set in the CSS, and the child screens have <code>position: absolute</code>. This enables the child screens to be aligned with the top-left corner of the container.</p>
  </li>
  <li><p><code>float</code> properties are used to position the controls to the left of the canvas <code>play-area</code>.</p>
  </li>
  </ul>
  <p>The HTML and CSS for the game so far are naive, representing a first pass at a working layout. There is plenty of room for optimisation and improvement.</p>
  <h3>Running it yourself</h3>
  <p>If you are interested in following along with the article, rather than just looking at screenshots, you can checkout the project and build an Android package for it by following the steps below.</p>
  <ol>
  <li><p>Download the latest stable Crosswalk Android bundle:</p>
  <pre><code>$ wget https://download.01.org/crosswalk/releases/crosswalk/android/stable/${XWALK-STABLE-ANDROID-X86}/crosswalk-${XWALK-STABLE-ANDROID-X86}.zip</code></pre>
  <p>If you want to run the version of the game designed to work with Crosswalk 8, fetch one of the Crosswalk Android <em>canary</em> bundles from <a href="/documentation/downloads.html">the download page</a>.</p>
  </li>
  <li><p>Unzip the bundle, e.g. on Linux:</p>
  <pre><code>$ unzip crosswalk-${XWALK-STABLE-ANDROID-X86}.zip</code></pre>
  </li>
  <li><p>Check out the code for the Crosswalk samples from github:</p>
  <pre><code>$ git checkout https://github.com/crosswalk-project/crosswalk-samples.git</code></pre>
  <p>The game used in this tutorial is in the <code>space-dodge-game</code> directory.</p>
  </li>
  <li><p>Use <code>make_apk.py</code> to build a Crosswalk package from the checked-out crosswalk-samples project:</p>
  <pre><code>$ cd crosswalk-${XWALK-STABLE-ANDROID-X86}
  $ python make_apk.py --manifest=/path/to/crosswalk-samples/space-dodge-game/&lt;version&gt;</code></pre>
  <p>Replace <code>&lt;version&gt;</code> with whichever version of the game you want to run; <code>master</code> is the version of the game before optimisation, and there are four other versions for different Crosswalk versions and techniques. See the <code>README.md</code> file in the <code>space-dodge-game</code> directory for details.</p>
  </li>
  <li><p>Once you have built a package for the game, you can deploy it to Android using <code>adb</code>:</p>
  <pre><code>$ adb install space_dodge_game_0.0.0.1_x86.apk</code></pre>
  <p>or</p>
  <pre><code>$ adb install space_dodge_game_0.0.0.1_arm.apk</code></pre>
  <p>depending on your target hardware.</p>
  <p>For more details about building and running Crosswalk applications on Android, see <a href="/documentation/android/run_on_android.html">the Getting started pages</a>.</p>
  </li>
  </ol>
  <h2>Issue 1: The game sometimes displays in portrait orientation</h2>
  <p>If the game is packaged and deployed to a small screen device in its initial state, this is what it looks like:</p>
  <p><img src="/assets/space_dodge_game-zte_geek_portrait.png" alt="space dodge game in portrait on ZTE Geek"></p>
  <p>It&#39;s obvious that it doesn&#39;t take up enough of the screen. The reason is that the game is in portrait orientation, when it should be in landscape. By rotating the device (so the game rotates), you can see an immediate improvement:</p>
  <p><img src="/assets/space_dodge_game-zte_geek_landscape.png" alt="space dodge game in landscape on ZTE Geek"></p>
  <p>However, the game shouldn&#39;t accidentally rotate if the screen orientation changes, as it does at the moment: it should always display in landscape mode.</p>
  <p>Crosswalk provides an easy fix for this, as it implements the <a href="http://www.w3.org/TR/screen-orientation/">Screen Orientation API</a>. Among other things, this enables an application to lock itself to a particular orientation at run time.</p>
  <p>To use this, add the following code to the main JavaScript entry point for your application. This depends on the application, but for the space dodge game, it&#39;s at the top of the <code>main.js</code> file, triggered once the DOM is ready:</p>
  <pre><code>document.addEventListener(&#39;DOMContentLoaded&#39;, function () {
    // check whether the runtime supports screen.lockOrientation
    if (screen.lockOrientation) {
      // lock the orientation
      screen.lockOrientation(&#39;landscape&#39;);
    }
  
    // ...rest of the application code...
  };</code></pre>
  <p>If you run the application now, you&#39;ll notice that the game rotates to landscape when it starts. Its appearance is the same as if the physical device were rotated to landscape. An application can also be locked to portrait orientation using this approach (<code>screen.lockOrientation(&#39;portrait&#39;)</code>).</p>
  <p>If you prefer, there are a couple of other ways to fix an application&#39;s orientation:</p>
  <ul>
  <li><p>Use the <code>orientation</code> field in the manifest (this only works for Crosswalk 8 or later).</p>
  <p>For example, the following manifest would force the application to landscape orientation:</p>
  <pre><code>{
    &quot;name&quot;: &quot;space_dodge_game&quot;,
    &quot;version&quot;: &quot;0.0.0.1&quot;,
    &quot;start_url&quot;: &quot;index.html&quot;,
    &quot;orientation&quot;: &quot;landscape&quot;
  }</code></pre>
  <p>You could then <a href="/documentation/android/run_on_android.html">build an application package for Android</a> from this manifest with:</p>
  <pre><code>$ python make_apk.py --manifest=/projects/space_dodge_game/manifest.json</code></pre>
  <p>Install it on an Android target as described in <a href="/documentation/android/run_on_android.html">the Getting started pages</a>.</p>
  <p>Using the <code>orientation</code> field in the manifest has exactly the same effect as using <code>screen.lockOrientation</code> in your application code: the application rotates to the requested orientation after the application starts. But <code>screen.lockOrientation</code> has the advantage of being supported by other runtimes (e.g. Firefox OS), so may be a better choice if you need your application to work cross-platform.</p>
  <p>The <code>orientation</code> manifest field is defined in the <a href="http://w3c.github.io/manifest/">W3C Manifest for web application specification</a>.</p>
  </li>
  <li><p>Use the <code>--orientation</code> option when running <code>make_apk.py</code>. Note that this won&#39;t work unless you are using <code>make_apk.py</code> to package your application. If you&#39;re using the embedding API, use <code>screen.lockOrientation</code> or the manifest approach.</p>
  <p>For example:</p>
  <pre><code>$ python make_apk.py --manifest=/projects/space_dodge_game/manifest.json \
      --orientation=landscape</code></pre>
  <p>This is really a hack, as it actually modifies the <code>AndroidManifest.xml</code> to rotate Crosswalk itself, rather than the application being rotated by Crosswalk. But it&#39;s a viable alternative for older versions of Crosswalk which don&#39;t support the <code>orientation</code> field in the manifest and where you prefer not to use <code>screen.lockOrientation</code>.</p>
  <p>This also has the same effect as using the <code>orientation</code> field, rotating the application after it has started.</p>
  <p>The <code>orientation</code> manifest field is defined in the <a href="http://w3c.github.io/manifest/">W3C Manifest for web application specification</a>.</p>
  </li>
  </ul>
  <h2>Issue 2: The status bar is distracting</h2>
  <p>The next issue is that the toolbar is still visible, which is a distraction while playing a game. There are two ways to make the application occupy the whole screen, hiding the status bar (on Android):</p>
  <ul>
  <li><p>Use the <code>display</code> field in <code>manifest.json</code> (this only works for Crosswalk 8 or later).</p>
  <p>For example, here&#39;s a manifest which sets fullscreen, and also retains the landscape orientation applied in the previous step:</p>
  <pre><code>{
    &quot;name&quot;: &quot;space_dodge_game&quot;,
    &quot;version&quot;: &quot;0.0.0.1&quot;,
    &quot;start_url&quot;: &quot;index.html&quot;,
    &quot;display&quot;: &quot;fullscreen&quot;,
    &quot;orientation&quot;: &quot;landscape&quot;
  }</code></pre>
  <p><a href="/documentation/android/run_on_android.html">Build and deploy to the device</a> as usual.</p>
  <p>The <code>display</code> manifest field is defined in the <a href="http://w3c.github.io/manifest/">W3C Manifest for web application specification</a>.</p>
  </li>
  <li><p>Use the <code>--fullscreen</code> option with the <code>make_apk.py</code> script.</p>
  <p>For example:</p>
  <pre><code>$ python make_apk.py --manifest=/projects/space_dodge_game/manifest.json \
      --orientation=landscape --fullscreen</code></pre>
  <p>This is a useful option if you are using an older version of Crosswalk which doesn&#39;t support the <code>display</code> field in the manifest. See <a href="/documentation/android/run_on_android.html">the Getting started pages</a> for more information about using <code>make_apk.py</code>.</p>
  </li>
  </ul>
  <p>Using either the <code>display</code> field or the <code>--fullscreen</code> option has the same effect: the application displays in fullscreen, hiding the system status bar on Android:</p>
  <p><img src="/assets/space_dodge_game-zte_geek_fullscreen.png" alt="space dodge game in fullscreen, landscape orientation"></p>
  <p>You may be familiar with the <a href="https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html">fullscreen API</a>, which enables an application to request that all or part of its user interface occupy the whole device screen. However, the fullscreen API has a different purpose from the approaches covered above: it requires some user activity to trigger the fullscreen request <em>after</em> an application is running.</p>
  <p>In the case of a Crosswalk application, you can use the fullscreen API, providing the user interacts with the application (e.g. push a button or make a gesture) to trigger the fullscreen request. But it is not possible to <em>automatically</em> make the application go fullscreen without user interaction using this API.</p>
  <h2>Issue 3: The game doesn&#39;t fit the screen</h2>
  <p>The game is now consistently bigger because it&#39;s always displayed fullscreen and in landscape orientation. But there&#39;s a lot of whitespace around it, and it&#39;s not visually appealing. It would be nicer if the game fitted the whole screen.</p>
  <p>The area occupied by the application is called its <em>viewport</em>. On a mobile device, this is the area under or between any toolbars on the screen (e.g. the status bar on Android) if the application is running in &quot;windowed&quot; mode; or the whole device screen if it is running in &quot;fullscreen&quot; mode. What we&#39;re aiming for here is &quot;fullscreen&quot; mode, to get the game to fill the whole of the device screen.</p>
  <p>There are a few approaches we could take:</p>
  <ol>
  <li><p>Scale the application to fit the smallest dimension (width or height), keeping aspect ratio and centering it in the viewport. The game has the same number of pixels, but they are scaled to fit into the viewport.</p>
  </li>
  <li><p>Do the same as above, but instead of scaling, physically change the size of all the game elements. This would make the canvas larger (in pixels) on a large screen and smaller on a small screen. The disadvantage of this approach is that you have to scale the image assets used in the game to ensure that they keep the same proportions: for example, if you have an image which is 40px square on a 400px square game area, then change the game canvas to 600px square, you will have to scale the image to 60px square. The advantage of this approach is that you&#39;re not scaling everything, just sprites; but the disadvantage is that it&#39;s more complicated to implement, as you have to track the size of the sprites (on screen) in isolation from their actual size (in the file).</p>
  </li>
  <li><p>Change the dimensions of the game, while keeping the size of the <code>&lt;canvas&gt;</code> the same. The area occupied by the game could be made physically larger, and perhaps make the controls larger too, while leaving the <code>&lt;canvas&gt;</code> element the same size. The reason for doing this is that the <code>&lt;canvas&gt;</code> is sensitive to size changes, as described in the previous bullet point.</p>
  </li>
  </ol>
  <p>For this game, the canvas is already too big for small screens, so the third approach is not really practical. (That approach only works if you know your game is only going to be played on a small range of screens, which can all fit the canvas at the size you specify. Similar to how old PC games were designed to fit devices with at least a 640x400 pixel screen, which was the size of most mid range monitors.)</p>
  <p>This leaves approaches 1 and 2, which are covered shortly. However, before getting onto those, there is a preparatory step which helps with measuring the actual size of the screen, making it more consistent between devices.</p>
  <h3>Preparation: Make the viewport fit the screen</h3>
  <p>A few years ago, when designing mobile phones, manufacturers realised that if 90% of websites were shown in a small screen, they would not fit. This is because websites used to be designed primarily for desktop screens; mobile sites were often separate from the main site, with reduced functionality or even written in a <a href="http://en.wikipedia.org/wiki/Wireless_Markup_Language">different markup language</a>. But users wanted to be able to access the &quot;real&quot; website from a phone, rather than a mobile-specific site; and they wanted to do this without compromising the site&#39;s appearance. Manufacturers resolved this by equipping their mobile browsers with a default &quot;zoom out&quot;, to make websites intended for desktops display (reasonably) well in mobile browsers. Most phone browsers still work this way: for example, the HTC One X I have for testing reports its width as 980px, while its actual physical width is 360px.</p>
  <p>Around the same time, web developers and designers changed their approach, designing websites which would display differently depending on device capabilities. These techniques are now known as <a href="http://alistapart.com/article/responsive-web-design">responsive web design</a>, and encompass a range of approaches including use of <a href="http://www.w3.org/TR/css3-mediaqueries/">media queries</a> and <a href="http://www.w3.org/community/respimg/">delivering different images to different screens</a>. Contemporary developers also often employ a <a href="http://www.abookapart.com/products/mobile-first">mobile first</a> philosophy, ensuring a website is highlighy functional first and foremost on small form factors, with added bells and whistles (typically, more and larger graphics) on bigger form factors.</p>
  <p>Where these two roads meet is at an awkward crossroads: developers are trying hard to provide sites tailored specifically for small screen devices; but small screen devices apply an artificial zoom which makes device screens appear larger than they are. As a result, the mobile version of a site could be bypassed (the site calculates that it is being viewed on a desktop browser); and the desktop site end up being delivered to a screen that is too small to display it properly.</p>
  <p>A solution was initially developed by <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html">Apple</a>, taking the form of an ad hoc HTML <code>&lt;meta&gt;</code> element named <code>viewport</code>. This could be used to ask a mobile browser to change various aspects of its viewport. For example, the page could ask the browser to set the viewport width to the device&#39;s real physical width with:</p>
  <pre><code>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;</code></pre>
  <p>Or prevent the user zooming the page in and out (e.g. with pinch gestures):</p>
  <pre><code>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, user-scalable=no&quot;&gt;</code></pre>
  <p>Other vendors followed suit and added support for this <code>&lt;meta&gt;</code> viewport element to their browsers.</p>
  <p>By using the <code>&lt;meta&gt;</code> viewport element, a developer could now prevent the browser from applying its default zoom to an HTML page. This would in turn mean that a web site or app could get a correct reading for the device&#39;s physical screen dimensions, enabling media queries to be applied accurately to select the best CSS for the screen.</p>
  <p>The <code>&lt;meta&gt;</code> viewport element is <em>not</em> a standard: it is not implemented consistently across browsers, and the syntax for declaring its content also varies between browsers. However, there are currently attempts to formalise <a href="http://dev.w3.org/csswg/css-device-adapt/">viewport rules in a CSS specification</a>. For now, though, the existing syntax works well for Crosswalk, and can be used as a stop-gap.</p>
  <p>To apply a viewport meta element to the space dodge game in this article, add it to the <code>&lt;head&gt;</code> of the <code>index.html</code> file. This instructs the browser to use its physical width as the viewport width, without zooming:</p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;meta charset=&quot;utf-8&quot;&gt;
      &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;
      &lt;title&gt;space dodge game&lt;/title&gt;
      &lt;link rel=&quot;stylesheet&quot; href=&quot;base.css&quot;&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
  
    ... rest of HTML file ...</code></pre>
  <p>The result is this:</p>
  <p><img src="/assets/space_dodge_game-viewport_meta.png" alt="space dodge game with landscape orientation, fullscreen and viewport meta"></p>
  <p>Note how the game is now filling the whole screen, and looks roughly the right size: the buttons are nice and big, and the graphics clear. However, the screen size on this device is 640px wide by 360px down, so the game canvas is spilling over the edges of the screen.</p>
  <p>By contrast, it doesn&#39;t take up enough space on a larger screen. Here it is on a Nexus 7:</p>
  <p><img src="/assets/space_dodge_game-nexus7.png" alt="space dodge game on Nexus 7 with landscape orientation, fullscreen, and viewport meta"></p>
  <p>In the next sections, I describe two ways to alter the size of the game to fit better into the screen.</p>
  <h3>Approach 1: Scale the game</h3>
  <p>The aim here is to scale the whole game (in CSS) so that it retains its aspect ratio but fits in the screen. The first step is to figure out the optimum position and size for the element which contains the whole game.</p>
  <p>Here is the algorithm in pseudo-code:</p>
  <ul>
  <li><p>Find the width and height of the viewport (which is the same as the screen dimensions, thanks to the viewport meta applied previously).</p>
  </li>
  <li><p>Find the width and height of the application container.</p>
  </li>
  <li><p>Find the ratio of viewport height to container height (scaleHeight).</p>
  </li>
  <li><p>Find the ratio of screen width to container width (scaleWidth).</p>
  </li>
  <li><p>Choose the smallest of scaleHeight and scaleWidth, and use this as the scale factor for both width and height (scaleBoth).</p>
  </li>
  <li><p>Work out the newHeight and newWidth of the container by multiplying its width and height by scaleBoth.</p>
  </li>
  <li><p>Work out a top and left offset for the container, as follows:</p>
  <ul>
  <li>left = (1 / scaleBoth) * ((viewport width - container newWidth) / 2)</li>
  <li>top = (1 / scaleBoth) * ((viewport height - container newHeight) / 2)</li>
  </ul>
  <p>Note that the offsets are being scaled, so that they are in proportion to the scaled game.</p>
  </li>
  <li><p>Apply the scaling and offsets to the whole game container using <a href="http://www.w3.org/TR/css-transforms-1/">CSS transforms</a>.</p>
  </li>
  </ul>
  <p>By implementing this pseudo-code in JavaScript, a scale can be applied to the whole container:</p>
  <pre><code>var scale = function () {
    var container = document.querySelector(&#39;#container&#39;);
    var containerWidth = container.offsetWidth;
    var containerHeight = container.offsetHeight;
  
    var viewportWidth = document.documentElement.clientWidth;
    var viewportHeight = document.documentElement.clientHeight;
  
    var scaleWidth = viewportWidth / containerWidth;
    var scaleHeight = viewportHeight / containerHeight;
    var scaleBoth = (scaleHeight &lt; scaleWidth) ? scaleHeight : scaleWidth;
  
    var newContainerWidth = containerWidth * scaleBoth;
    var newContainerHeight = containerHeight * scaleBoth;
  
    var left = (viewportWidth - newContainerWidth) / 2;
    left = parseInt(left * (1 / scaleBoth), 10);
  
    var top = (viewportHeight - newContainerHeight) / 2;
    top = parseInt(top * (1 / scaleBoth), 10);
  
    // scale the whole container
    var transform = &#39;scale(&#39; + scaleBoth + &#39;,&#39; + scaleBoth + &#39;) &#39; +
                    &#39;translate(&#39; + left + &#39;px, &#39; + top + &#39;px)&#39;;
    container.style[&#39;-webkit-transform-origin&#39;] = &#39;top left 0&#39;;
    container.style[&#39;-webkit-transform&#39;] = transform;
    container.style[&#39;transform-origin&#39;] = &#39;top left 0&#39;;
    container.style[&#39;transform&#39;] = transform;
  };
  
  window.onresize = scale;
  scale();</code></pre>
  <p>To give an example of the CSS transforms which will be applied, consider the case where the scale is 2.05 and the top and left offsets are 0px and 40px respectively. The resulting CSS transforms would be:</p>
  <pre><code>-webkit-transform-origin: 0 0 0;
  transform-origin: 0 0 0;
  -webkit-transform: scale(2.05, 2.05) translate(40px, 0px);
  transform: scale(2.05, 2.05) translate(40px, 0px);</code></pre>
  <p>Setting the transform origin to <code>top left 0</code> ensures that the transforms are applied from the top-left corner of the container. The <code>scale(2.05, 2.05)</code> function changes the scaling of the container; and the <code>translate(40px, 0px)</code> function moves the container to the correct position on screen (40 pixels from the left-hand edge). Here&#39;s the result on a ZTE Geek:</p>
  <p><img src="/assets/space_dodge_game-zte_geek_scale.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, CSS transform"></p>
  <p>Notice how the application is fitted vertically, then centered horizontally.</p>
  <p>This approach is good because it is simple. However, as the scaling is applied to the whole application, it can cause some blurring, especially when scaling up. The next section describes a more complex alternative which uses resizing plus selective scaling of game assets.</p>
  <h3>Approach 2: Resize the game</h3>
  <p>This approach requires a more extensive reworking of the CSS for the game, as it affects the positioning, size and appearance of every element. It&#39;s tempting to ignore this approach, as the scaling approach of the previous section works pretty well. But there&#39;s actually good discipline involved in making this alternative approach work.</p>
  <p>The first step is to make the container occupy the whole screen. In the olden days, this would have meant measuring the screen, then manually setting the width and height CSS properties of the container (in JavaScript). However, Crosswalk supports a handy CSS feature which means you don&#39;t have to do this any more: <a href="http://dev.w3.org/csswg/css-values/#viewport-relative-lengths">viewport-percentage lengths</a>. These allow you to specify the dimensions of elements in terms of a percentage of the viewport dimensions. As the application is now fullscreen, the viewport fills the whole screen; so the container can fill 100% of the device&#39;s height and width using this CSS rule:</p>
  <pre><code>#container {
    position: relative;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
  }</code></pre>
  <p>Note the <code>vw</code> (viewport percentage width) and <code>vh</code> (viewport percentage height) suffixes to the container&#39;s width and height settings. Here&#39;s what the game looks like on a ZTE Geek with this change to the container sizing:</p>
  <p><img src="/assets/space_dodge_game_zte_geek_resize.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize"></p>
  <p>Not bad for a first pass. But the bottom of the canvas has disappeared off-screen; and the buttons look squashed. We&#39;ll fix this in a minute.</p>
  <p>Note that viewport-percentage lengths don&#39;t work well for testing in a desktop browser, as desktop environments often have toolbars on the browser and on the desktop itself. This means that the viewport height can be considerably larger than the amount of space inside the browser window. However, you could try experimenting with <a href="https://developer.chrome.com/devtools/docs/mobile-emulation">Chrome&#39;s device emulation support</a> if you want a quick way to test your app without a mobile or tablet.</p>
  <p>At this point in testing, I realised something. When I first wrote the game, I concentrated on getting it to look right in a desktop browser. This meant that I didn&#39;t necessarily do everything &quot;properly&quot;. For example, with a fixed width container, I could arrange the control buttons easily: setting a few margins and a bit of padding seemed to work.</p>
  <p>However, once I started thinking about resizing <em>everything</em>, it became clear that I hadn&#39;t done things the &quot;right way&quot;. I needed to make some fixes so that the buttons and score would be positioned and sized correctly. This could be done easily in CSS, without having to resort to JavaScript.</p>
  <p>I changed this rule:</p>
  <pre><code>#control-up, #control-down {
    margin: 20% 0;
  }</code></pre>
  <p>to:</p>
  <pre><code>#control-down {
    margin: 0.5em 0 0 0;
  }</code></pre>
  <p>(set the top margin of the &quot;down&quot; button to a fixed amount so it stays close to the &quot;up&quot; button&quot;).</p>
  <p>I also changed this rule:</p>
  <pre><code>#controls {
    height: 100%;
    width: 20%;
    padding: 5%;
    text-align: center;
    box-sizing: border-box;
    float: left;
  }</code></pre>
  <p>to:</p>
  <pre><code>#controls {
    height: 100%;
    width: 20%;
    padding: 0.5em;
    text-align: center;
    box-sizing: border-box;
    float: left;
  }</code></pre>
  <p>(padding changed from <code>5%</code> to <code>0.5em</code>). This fixes the spacing of the controls so that they stay a reasonable distance apart as the screen size changes.</p>
  <p>Here&#39;s the result:</p>
  <p><img src="/assets/space_dodge_game-zte_geek_resize_2.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize, fixed margin"></p>
  <p>The buttons now look right, but the canvas is too tall for the screen (remember, its pixel height is set as an attribute on the canvas, not in CSS). This currently means you can move the spaceship off the bottom of the screen. The canvas needs to be resized to fit in the space to the right of the controls, while maintaining its aspect ratio.</p>
  <p>To do this, I applied the technique from the previous section, where I scaled the whole game to fit the screen. But in this case, just the canvas is scaled to fit into the area to the right of the controls. In addition, the canvas scaling should be done using its width and height attributes, rather than scaling it in CSS. (This is a bit confusing, as the height and width attributes of a canvas are different from the CSS height and width of its <code>&lt;canvas&gt;</code> element.)</p>
  <p>First, I added a new parent element for the canvas (the <code>&lt;div&gt;</code> with ID <code>play-area-container</code> below):</p>
  <pre><code>&lt;div id=&quot;container&quot;&gt;
  
    &lt;div id=&quot;game-screen&quot;&gt;
      &lt;div id=&quot;controls&quot; class=&quot;vbox&quot;&gt;
        &lt;p id=&quot;score&quot;&gt;Score&lt;br&gt;&lt;span id=&quot;score-display&quot;&gt;&lt;/span&gt;&lt;/p&gt;
        &lt;img id=&quot;control-up&quot; src=&quot;control-up.png&quot;&gt;
        &lt;img id=&quot;control-down&quot; src=&quot;control-down.png&quot;&gt;
      &lt;/div&gt;
  
      &lt;div id=&quot;play-area-container&quot;&gt;
        &lt;canvas id=&quot;play-area&quot; width=&quot;600&quot; height=&quot;450&quot;&gt;&lt;/canvas&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  
    &lt;div id=&quot;finish-screen&quot; class=&quot;vbox&quot; data-visible=&quot;false&quot;&gt;
      &lt;p id=&quot;final-score&quot;&gt;&lt;/p&gt;
      &lt;button id=&quot;restart&quot;&gt;Restart&lt;/button&gt;
    &lt;/div&gt;
  
  &lt;/div&gt;</code></pre>
  <p>I modified the CSS so it&#39;s <code>play-area-container</code> and not <code>play-area</code> which is sized to fit the right-hand section of the game by changing:</p>
  <pre><code>#play-area {
    float: right;
    width: 80%;
  }</code></pre>
  <p>to:</p>
  <pre><code>#play-area-container {
    float: right;
    width: 80%;
    height: 100%;
  }
  
  #play-area {
    position: relative;
    box-sizing: border-box;
    border: 2px solid darkblue;
  }</code></pre>
  <p>I added a border to <code>play-area</code> so you can see where the play area really is, as it now won&#39;t necessarily fill its parent. This allows the player to see where the asteroids are going to come from (it might not be the right-hand edge of the screen any more). I also changed <code>play-area</code> to use <code>position: relative</code>, so it can be positioned relative to its parent (i.e. <code>play-area-container</code>).</p>
  <p>Then I used a variant of the scale algorithm from the previous section to fit the canvas into the <code>play-area-container</code>:</p>
  <pre><code>// the canvas element
  var playArea = document.querySelector(&#39;#play-area&#39;);
  
  // factor by which to modify canvas width and height
  var scaleCanvas = 1;
  
  var fitCanvas = function () {
    var container = document.querySelector(&#39;#play-area-container&#39;);
    var containerWidth = container.offsetWidth;
    var containerHeight = container.offsetHeight;
  
    var playAreaWidth = playArea.width;
    var playAreaHeight = playArea.height;
  
    var scaleWidth = containerWidth / playAreaWidth;
    var scaleHeight = containerHeight / playAreaHeight;
    scaleCanvas = (scaleHeight &lt; scaleWidth) ? scaleHeight : scaleWidth;
  
    var newPlayAreaWidth = playAreaWidth * scaleCanvas;
    var newPlayAreaHeight = playAreaHeight * scaleCanvas;
  
    var left = (containerWidth - newPlayAreaWidth) / 2;
    var top = (containerHeight - newPlayAreaHeight) / 2;
  
    // resize and position the canvas
    playArea.width = parseInt(newPlayAreaWidth, 10);
    playArea.height = parseInt(newPlayAreaHeight, 10);
    playArea.style.top = top + &#39;px&#39;;
    playArea.style.left = left + &#39;px&#39;;
  };
  
  window.onresize = fitCanvas;
  fitCanvas();</code></pre>
  <p>Note that this changes the canvas width and height attributes then positions it, rather than scaling the canvas in CSS.</p>
  <p>This is the result on a ZTE Geek (canvas size is &quot;shrunk&quot; to 480px by 360px):</p>
  <p><img src="/assets/space_dodge_game_zte_geek_resize_canvas.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize, fixed margin, canvas resized"></p>
  <h4>Resize the sprites</h4>
  <p>One side-effect of changing the canvas size is that the sprites are no longer in the same proportions as they were. Previously, the canvas was 600px wide and 450px high; the sprite for the spaceship is 75px wide by 44px tall, which is 12.5% of the canvas width and 10% of its height. But now the canvas size has changed; and the spaceship is now 16% of the width of the canvas and 12% of its height (i.e. it is relatively larger). This makes the game harder, as the asteroids will reach the ship sooner (they haven&#39;t got so far to travel). Conversely, on a large screen, the game is too easy: the spaceship takes up less of the canvas and the asteroids are further away.</p>
  <p>The solution is to draw the images onto a larger area of the canvas, so that their dimensions are always in the same ratio to the canvas dimensions. In the previous code fragment, I laid the foundation for this by recording the canvas scale factor in a variable outside the <code>fitCanvas()</code> function:</p>
  <pre><code>// factor by which to modify canvas width and height
  var scaleCanvas = 1;</code></pre>
  <p>After the first call to <code>fitCanvas()</code>, <code>scaleCanvas</code> is set to the canvas scale factor. To scale the sprites up, we can apply the same factor to the size of the sprites when they are drawn. In the code for the game, the images were previously written to the canvas like this:</p>
  <pre><code>ctx.drawImage(image, x, y, image.width, image.height);</code></pre>
  <p>(<code>ctx</code> is the canvas&#39; 2D context)</p>
  <p>This code can be modified as follows to draw the image at the correct scale:</p>
  <pre><code>ctx.drawImage(
    image,
    x,
    y,
    image.width * scaleCanvas,
    image.height * scaleCanvas
  );</code></pre>
  <p>The result is as follows (on the ZTE Geek again):</p>
  <p><img src="/assets/space_dodge_game-zte_geek_resize_canvas_2.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize, fixed margin, canvas and sprites resized"></p>
  <p>Compare with the previous screenshot and you should be able to see that the ship and asteroids are slightly smaller in this screenshot (80% of the size of the previous one).</p>
  <p>The distances moved by the game objects are described in terms of multiples of their height (each control press moves the ship three times its own height per second, and asteroids move 3-5 times their width per second). This means that there is no need to modify any of the movement code, providing the scaled heights and widths are used in the calculations, for example:</p>
  <pre><code>// the ship height on screen is the Image height of the
  // loaded graphics file * the canvas scale factor
  var shipHeight = shipImg.height * scaleCanvas;
  
  // get the number of seconds since the last animation frame
  var timeDelta = (currentTime - lastTime) / 1000;
  
  // calculate movement on the y axis;
  // the player moves three times their own height per second;
  // direction = 1 for down, -1 for up
  var moveY = direction * shipHeight * timeDelta * 3;</code></pre>
  <p>Any other code which refers to the height and width of the sprites (such as the code for collision testing) will also have to apply the canvas scale. The simplest approach is to add functions for fetching the scaled height of the ship and the asteroids, then using those whenever the height and width of an <code>Image</code> object are required. For example:</p>
  <pre><code>// img is an Image object loaded with a ship or asteroid graphics
  // file
  function getImgWidth(img) {
    return img.width * scaleCanvas;
  }
  
  function getImgHeight(img) {
    return img.height * scaleCanvas;
  }</code></pre>
  <p>The movement code could then be rewritten as:</p>
  <pre><code>// get the number of seconds since the last animation frame
  var timeDelta = (currentTime - lastTime) / 1000;
  
  // calculate movement on the y axis;
  // the player moves three times their own height per second;
  // direction = 1 for down, -1 for up
  var moveY = direction * getImgHeight(shipImg) * timeDelta * 3;</code></pre>
  <p>Depending on the game and the environment, it may be possible to cache the width and height calculations. However, you have to be careful with this, ensuring that you invalidate the cached values if <code>canvasScale</code> changes (for example, if you resize the game when the window size changes). In my code, <code>fitCanvas()</code> is called each time the <code>onresize</code> event fires on the screen. This happens at least twice on a mobile device, while Crosswalk locks the screen orientation to landscape. For this reason, and to keep things simple, I dynamically get the height and width of the image each time, as this is relatively inexpensive for the two images I&#39;m using.</p>
  <h2>Issue 4: Sprites blur on large screens</h2>
  <p>Having applied the lessons in the previous section, one other possible issue is the potential for blurring due to scaling. If you take a close look at this image:</p>
  <p><img src="/assets/space_dodge_game-large_screen_blur.png" alt="space dodge game: sprites blur on large screens"></p>
  <p>you may notice that it appears blurry. This image was copied from a screenshot of a large browser window, where the sprite graphic was being scaled up to twice its original size, making it blur.</p>
  <p>One solution is to provide a larger graphic which can scale with less blurring, and use this graphic when the canvas is scaled up (<code>scaleCanvas &gt; 1</code>). The <code>src</code> attribute of the ship and asteroid <code>Image</code> objects can then be set inside the <code>fitCanvas()</code> function, depending on <code>scaleCanvas</code>:</p>
  <pre><code>// player ship image (to draw onto canvas)
  var ship = new Image();
  
  // asteroid image (to draw onto canvas)
  var asteroid = new Image();
  
  // the canvas element
  var playArea = document.querySelector(&#39;#play-area&#39;);
  
  // factor to modify canvas width and height by
  var scaleCanvas = 1;
  
  var fitCanvas = function () {
    var container = document.querySelector(&#39;#play-area-container&#39;);
    var containerWidth = container.offsetWidth;
    var containerHeight = container.offsetHeight;
  
    var playAreaWidth = playArea.width;
    var playAreaHeight = playArea.height;
  
    var scaleWidth = containerWidth / playAreaWidth;
    var scaleHeight = containerHeight / playAreaHeight;
    scaleCanvas = (scaleHeight &lt; scaleWidth) ? scaleHeight : scaleWidth;
  
    var newPlayAreaWidth = playAreaWidth * scaleCanvas;
    var newPlayAreaHeight = playAreaHeight * scaleCanvas;
  
    var left = (containerWidth - newPlayAreaWidth) / 2;
    var top = (containerHeight - newPlayAreaHeight) / 2;
  
    // resize and position the canvas
    playArea.width = parseInt(newPlayAreaWidth, 10);
    playArea.height = parseInt(newPlayAreaHeight, 10);
    playArea.style.top = top + &#39;px&#39;;
    playArea.style.left = left + &#39;px&#39;;
  
    // use a double-sized image if the canvas is being scaled up
    if (scaleCanvas &gt; 1) {
      ship.src = &#39;rocket2x.png&#39;;
      asteroid.src = &#39;asteroid2x.png&#39;;
  
      // reset the scale so that the double-sized images are scaled
      // down to the same size as the original image
      scaleCanvas /= 2;
    }
    // otherwise use the original-sized image
    else {
      ship.src = &#39;rocket.png&#39;;
      asteroid.src = &#39;asteroid.png&#39;;
    }
  };
  
  window.onresize = fitCanvas;
  fitCanvas();</code></pre>
  <p>Compare the double-sized image when scaled down slightly (on the left) with the smaller image scaled up to twice its original size (on the right):</p>
  <p><img src="/assets/space_dodge_game-large_screen_less_blur.png" alt="space dodge game: large image scaled down vs small image scaled up"></p>
  <p>As you can see here, the large image scaled down is far less blurry than the small image scaled up.</p>
  <p>Depending on how large the images are, it might make sense to use larger images at all scales. But if you are trying to keep the size of the assets down, using different images for different scales may be a more viable approach.</p>
  <h2>Issue 5: We need a launch screen</h2>
  <p>Applications can sometimes take a while to load, due to network latency and/or sheer size and number of resources. This problem gets worse as the application grows and is especially problematic for games, where there are often a large number of graphical, audio and video assets in use. In such cases, a common technique is to show a screen with introductory images or text while the resources are loading, commonly known as a &quot;loading&quot; or &quot;launch&quot; screen. Frameworks often provide APIs to support this, or developers may add their own code to handle it.</p>
  <p>Crosswalk 8 and later provides baked-in support for launch screens, via an <code>xwalk_launch_screen</code> in the application manifest. This enables you to set background and foreground images and colours, differentiated according to screen orientation and pixel density if desired, with little or no programming. Full details of its capabilities are on the <a href="/documentation/manifest/launch_screen.html">launch screen page</a>.</p>
  <p>The steps below explain how to add a launch screen to the example game.</p>
  <ol>
  <li><p>First, add a foreground image <code>fg.png</code>. This is a simple graphic composed of the name of the game plus the rocket sprite, with a transparent background (I&#39;ve added a blue background to the graphic here so the white letters show up):</p>
  <p><img src="/assets/space_dodge_game-launch_screen_fg.png" alt="space dodge game launch screen foreground"></p>
  <p>I made the image relatively small (320px by 240px), as it should fit small mobile screens.</p>
  </li>
  <li><p>To activate the launch screen, add an <code>xwalk_launch_screen</code> field to the <code>manifest.json</code> file:</p>
  <pre><code>{
    &quot;name&quot;: &quot;space_dodge_game&quot;,
    &quot;version&quot;: &quot;0.0.0.1&quot;,
    &quot;start_url&quot;: &quot;index.html&quot;,
    &quot;orientation&quot;: &quot;landscape&quot;,
    &quot;display&quot;: &quot;fullscreen&quot;,
    &quot;xwalk_launch_screen&quot;: {
      &quot;ready_when&quot;: &quot;custom&quot;,
      &quot;landscape&quot;: {
        &quot;background_color&quot;: &quot;#11f&quot;,
        &quot;image&quot;: &quot;fg.png&quot;
     }
    }
  }</code></pre>
  <p>The <code>ready_when</code> property specifies when to stop showing the launch screen. By setting this to <code>custom</code>, the launch screen can be closed programmatically once all the assets are loaded. This is the typical mode you would want to use for launch screens in an HTML5 game, as you will often be doing some initialisation work in JavaScript before the game is usable. In the next step, we&#39;ll add the code which does this.</p>
  <p>The <code>landscape</code> property specifies the background colour and <code>image</code> (foreground image) to use for the launch screen when in landscape mode. Any image paths are relative to <code>manifest.json</code>, and the foreground image will be centered on the background.</p>
  <p>As the application will always be in landscape orientation (<code>&quot;orientation&quot;: &quot;landscape&quot;</code> is set in the manifest), there&#39;s no need for a <code>portrait</code> property. Note that you may use the <code>default</code> key to specify the settings for all orientations; and can specify different backgrounds and images for different orientations and screen densities. See <a href="/documentation/manifest/launch_screen.html">this explanation</a> for more details about the available launch screen options.</p>
  </li>
  <li><p>The final step is to modify the JavaScript to close the launch screen.</p>
  <p>When the <code>ready_when</code> property is set to <code>custom</code>, the launch screen can be closed by calling the Crosswalk-specific <code>window.screen.show()</code> method. For this game, I added an artificial 5 second timeout before calling the <code>window.screen.show()</code> method (otherwise the game loads so quickly that you only see a flash of the launch screen). The code looks like this:</p>
  <pre><code>setTimeout(function () {
    // check that the window.screen.show method is available
    if (window.screen.show) {
      window.screen.show();
    }
  
    gameLoop();
  }, 5000);</code></pre>
  <p>The <code>gameLoop()</code> function starts the animation loop for the game, once the launch screen has been closed.</p>
  </li>
  </ol>
  <p>Now the application can be packaged as usual with <code>make_apk.py</code> and installed on a target. This is what the launch screen looks like on a ZTE Geek:</p>
  <p><img src="/assets/space_dodge_game_launch_screen-zte_geek.png" alt="space dodge game launch screen on ZTE Geek"></p>
  <h2>Summary</h2>
  <p>Fitting an HTML5 application into a mobile screen has been challenging in the past; the advent of new APIs and configuration options is gradually making things easier. Crosswalk provides pioneering support for such features: viewport management; advanced layout with CSS flexbox and viewport percentage lengths; manifest options for orientation, display and launch screens; plus many others. The result is a rich runtime environment for all applications, especially games.</p>
  
    <footer class="article-next">
      
  
  
  
    
    
      
      
    
      
      
    
      
      
    
      
      
    
      
      
    
      
      
        
      
    
      
      
        
        <a href="/documentation/tutorials/webassembly.html" class="article-promo well">
          <em>What’s next?</em>
          <h3>Web Assembly</h3>
        </a>
      
    
  
  
    </footer>
  </article>
  
            
          </div>
        </div>
      </div>
      
  
      
   
    <hr class="footer-divider" style="margin-top:125px; margin-bottom:0px" />
      <div style="position:relative; top:-30px;">
         <a href="/"><img src="/assets/cw-logo-circle.png" width="60px" style="display:block; margin: 0 auto;" /></a>
      </div>
      <footer class="footer footer--documentation" >
        <div class="container" >
          <div class="row">
            <div  class="footer-div" language="en">
            <img src="/assets/Twitter_logo_blue.png" width="20px" /> Follow  <a href="http://twitter.com/xwalk_project">@xwalk_project on Twitter</a> for the latest developer activities and project updates.
            </div>
             <div  class="footer-div" language="zh" style="display:none">
             <img src="/assets/Sina_Weibo_Blue.png" width="60px" /> 参考<a href="http://weibo.com/crosswalk">微博</a> 最新的开发者活动或者更新。
            </div>
            <div class="footer-div">
               Latest blog post:</br>
                
                
                  <b><a href="/blog">Crosswalk 23 to be the last Crosswalk release</a></b><br/>
                  &nbsp;(<span ><time class="js-vagueTime" datetime="Fri, 10 Feb 2017 09:30:00 GMT">2017-02-10T09:30</time></span>)
                
                <br/>
             </div>
            <div class="footer-div">
                <strong><a href="/feed.xml"><img src="/assets/rss-icon-16.gif" style="vertical-align:middle" /> RSS Feed</a></strong>
            </div>
            <div class="footer-div">
               <a href="/documentation/getting_started.html"> Documentation</a> &nbsp;
               <a href="/blog"> Blog</a> &nbsp;
               <a href="/documentation/downloads.html"> Downloads</a> <br />
               <a href="https://crosswalk-project.org/jira/secure/Dashboard.jspa"> Issues</a> &nbsp;
               <a href="https://github.com/crosswalk-project"> GitHub Source</a> &nbsp;
               <a href="/sitemap.html">Sitemap</a> <br/>
            </div>
          </div>
          <div class="row">
              <small>
                The Crosswalk Project was created by the Intel Open Source Technology Center. Copyright © 2013–2016 Intel Corporation. All right reserved. <a href="https://github.com/crosswalk-project/crosswalk-website/wiki/Privacy-Policy">  Privacy policy </a>  *Other names and brands may be claimed as the property of others.
              </small>
          </div>
        </div>
      </footer>
  <script>
      $("[language=en]").css("display","none");
      $("[language=en]").css("display","block");
  </script>
  
      
      
        <!-- Google Tag Manager -->
        <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-WC843Q"
        height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
        <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-WC843Q');</script>
        <!-- End Google Tag Manager -->
      
      <script src="/js/smoothScroll.js"></script>
      <script src="/js/vagueTime.js"></script>
      <!-- <script async defer src="/js/trmix.js"></script> -->
    </body>
  </html>
  