You are previewing Supercharged JavaScript Graphics.

Supercharged JavaScript Graphics

Cover of Supercharged JavaScript Graphics by Raffaele Cecco Published by O'Reilly Media, Inc.
  1. Supercharged JavaScript Graphics
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. Preface
      1. Audience and Assumptions
      2. Organization
      3. Conventions Used in This Book
      4. Using Code Examples
      5. Safari® Books Online
      6. How to Contact Us
      7. Acknowledgments
    3. 1. Code Reuse and Optimization
      1. Keeping It Fast
      2. What and When to Optimize
      3. Homespun Code Profiling
      4. Optimizing JavaScript
      5. Optimizing jQuery and DOM Interaction
      6. Other Resources
    4. 2. DHTML Essentials
      1. Creating DHTML Sprites
      2. Converting into a jQuery Plug-in
      3. Timers, Speed, and Frame Rate
      4. Internet Explorer 6 Background Image Caching
    5. 3. Scrolling
      1. CSS-Only Scrolling Effects
      2. Scrolling with JavaScript
    6. 4. Advanced UI
      1. HTML5 Forms
      2. Using JavaScript UI Libraries
      3. Creating UI Elements from Scratch
    7. 5. Introduction to JavaScript Games
      1. Game Objects Overview
      2. The Game Code
    8. 6. HTML5 Canvas
      1. Canvas Support
      2. Bitmaps, Vectors, or Both?
      3. Canvas Limitations
      4. Canvas Versus SVG
      5. Canvas Versus Adobe Flash
      6. Canvas Exporters
      7. Canvas Drawing Basics
      8. Animating with Canvas
      9. Canvas and Recursive Drawing
      10. Replacing DHTML Sprites with Canvas Sprites
      11. A Graphical Chat Application with Canvas and WebSockets
    9. 7. Vectors for Games and Simulations
      1. Operations on Vectors
      2. Creating a JavaScript Vector Object
      3. A Cannon Simulation Using Vectors
      4. Rocket Simulation
    10. 8. Google Visualizations
      1. Limitations
      2. Chart Glossary
      3. Image Charts
      4. Interactive Charts
    11. 9. Reaching the Small Screen with jQuery Mobile
      1. jQuery Mobile
      2. TilePic: A Mobile-Friendly Web Application
      3. PhoneGap
    12. 10. Creating Android Apps with PhoneGap
      1. Installing PhoneGap
      2. Creating a PhoneGap Project in Eclipse
    13. Index
    14. About the Author
    15. Colophon
    16. SPECIAL OFFER: Upgrade this ebook with O’Reilly

Using JavaScript UI Libraries

While HTML5 rich input elements might currently be a little too raw to use reliably, we can use JavaScript to provide attractive and consistent results across browsers. There are two approaches to doing this: use an existing JavaScript user interface library, or create user interface widgets from scratch.

In this section, I will give you a brief overview of two of the most popular JavaScript user interface libraries, jQuery UI and Ext JS. Some people may see these two libraries as competing products (and there is invariably some overlap), but take a closer look and you’ll see that they are (arguably) quite different in their intended uses. For example, if you were developing an ecommerce web application, you might find the lighter jQuery UI suitable for the frontend, customer-facing side, and Ext JS suitable for the complex backend, administration side. One big difference between the two, and an indicator of where these projects are going, is the size of the full zipped downloads (including samples and documentation): jQuery UI weighs in at a lightweight 1 MB, whereas Ext JS is a meaty 13 MB.

Using jQuery UI for Enhanced Web Interfaces

The jQuery UI library is built on top of jQuery to provide additional user interface elements. Certainly, anyone using jQuery is well advised to investigate jQuery UI, as a large chunk of the code—jQuery itself—will already be loaded on the page. You can find jQuery UI at

Figure 4-2 shows various jQuery UI elements styled with one of the attractive 24 themes available. In this example, we are using the Start theme. With a few minor variations, all of these elements will display correctly and consistently on virtually all browsers.

jQuery UI elements

Figure 4-2. jQuery UI elements

jQuery UI currently features the following user interface elements:

  • Accordion

  • Autocomplete

  • Button

  • Datepicker

  • Dialog

  • Progressbar

  • Slider

  • Tabs

This is not a vast selection, but the widgets are attractive and stable, and additional widgets are in the pipeline. The library is easy to use, relatively lightweight, and suitable for most basic form-related and page layout tasks. To gain a realistic expectation of the library, think about it as offering an enhanced website experience rather than a heavy-duty application experience.

As well as user interface widgets, jQuery UI provides useful lower-level interactions that you can apply to arbitrary DOM elements:


Move elements around with the mouse.


Generate an event when one element is dropped on another.


Resize elements by dragging the edges and corners.


Click to highlight single or multiple elements.


Reorder elements by dragging them.

You can use these to create your own specialized widgets.

Loading and using jQuery UI

Installing and using jQuery UI is straightforward, with a just few JavaScript and CSS includes at the top of the page. All of the required files—jQuery, jQuery UI, and CSS themes with related imagery—can be conveniently loaded from the Google content delivery network (CDN), although you can install everything on your own web server if desired.

Example 4-1 shows how to set up a basic jQuery UI page with a single date picker widget. Figure 4-3 shows the output.

Example 4-1. Basic jQuery UI setup

<!DOCTYPE html>
    <title>jQuery UI</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <!--    jQuery UI font sizes are relative to document's,
            so set a base size here. -->
    <style type="text/css">
        body {
            font-size: 12px;
            font-family: sans-serif

    <!-- Load the jQuery UI style sheet. -->
    <link rel="stylesheet" href=""
        type="text/css" media="all" />

    <!-- Load jQuery. -->
    <script src=""

    <!-- Load jQuery UI. -->
    <script src=""

        // On DOM loaded, initialize a date picker widget on the input element
        // with id of 'datepicker'.
        $(function() {

    <!-- The following input element will be turned into a date picker. -->
    <p>Enter Date: <input type="text" id="datepicker"></p>
jQuery UI date input

Figure 4-3. jQuery UI date input

Theming jQuery UI

It’s easy to use one of the other jQuery UI themes if the Start theme doesn’t suit your needs. On the line that loads the jQuery UI CSS style sheet file, change the /start/ part of the path to one of the other theme names; for example:




Where a theme name contains a space—for example, UI Lightness—substitute a hyphen instead and convert the name to lowercase: ui-lightness.

For a full list of the 24 available standard themes, visit

As mentioned previously, in addition to linking directly to the themes via Google’s CDN, you can download the themes and store them on your own server if desired.

As well as the standard themes, the Page Themes page also contains a ThemeRoller application (Figure 4-4), which allows you to modify existing themes or create new ones from scratch. You can then download and use these custom themes instead of the standard ones. Note that the jQuery UI font sizes are relative to the page’s base font size, so it’s worth setting up a default font size for the page; otherwise, fonts may appear too large.

jQuery UI ThemeRoller

Figure 4-4. jQuery UI ThemeRoller

Heavy Duty UI with Ext JS

In contrast to jQuery UI, Ext JS offers a full-on, heavy-duty user interface system. It offers a seemingly endless array of user interface functionality built into a more rigidly defined application framework. Ext JS enables the development of web applications that are virtually indistinguishable from native operating system GUI applications. It’s suitable for complex backend administration interfaces (e.g., ecommerce administration) or elaborate frontend web applications (e.g., an art package). The flip side is that using Ext JS might be like cracking a nut with a sledgehammer if all you want is a couple of extra widgets and some tabbed content. Take a look at jQuery UI if your requirements are lighter.

You can find Ext JS on the Sencha website:

It is almost pointless to list the full functionality of Ext JS, as there is very little it doesn’t do. Some examples on the Sencha website go way beyond basic widgets and include applications such as entire web desktops, complex data grids, and forum browsers. There are layout managers to split up and organize UI page content, as well as facilities to bind various widgets to remote data sources. Some unexpected Ext JS features include Google Maps and chart windows (Figure 4-5 and Figure 4-6).

Ext JS maps

Figure 4-5. Ext JS maps

Ext JS charts

Figure 4-6. Ext JS charts

Loading and using Ext JS

Like the jQuery UI, loading the resources for Ext JS is straightforward, with the convenience of a content delivery network version of the required CSS and JavaScript files. These files are hosted on the Cachefly network, but you can install them on your own server if desired.

Although you can use Ext JS to manipulate DOM elements directly like jQuery, the Ext JS “way” is naturally more biased toward creating objects and having them magically appear on the page. In many regards, working with Ext JS is more akin to traditional, non-DOM-based application development. This method of working may have some benefits in terms of readability in larger projects. Ultimately, whether you prefer the Ext JS or jQuery way is largely a matter of personal taste.

Example 4-2 creates a window object (not to be confused with the standard DOM window) and attaches a date widget, a spacer object, and a slider widget (Figure 4-7).

Example 4-2. Basic Ext JS setup

<!DOCTYPE html>
    <title>Ext JS</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <!-- Load the Ext JS CSS. -->
    <link rel="stylesheet" type="text/css"
        href="" />

    <!-- Load the Ext JS base JavaScript. -->
    <script type="text/javascript"

    <!-- Load the rest of Ext JS.  -->
    <script type="text/javascript"

    <script type="text/javascript">

    // Tell Ext JS where to find a transparent gif image
    // (used for rendering various elements).


    // Ext JS onReady is called when the DOM has loaded,
    // similar to jQuery's $(function(){}).

            // Create a DateField object.
            var dateField = new Ext.form.DateField({
                fieldLabel: 'Date Widget',
                emptyText:'Enter date...',
                width: 128

            // Create a Slider object.
            slider = new Ext.Slider({
                width: 280,
                minValue: 0,
                maxValue: 100,
                plugins: new Ext.slider.Tip()

            // Create a Spacer object.
            space = new Ext.Spacer({

            // Create a Window object to attach all of the above.
            win = new Ext.Window({
                title: 'Ext JS Demo',
                bodyStyle:'padding: 10px',
                items:[dateField, space, slider],

            // Show the window.
Ext JS window object, date picker, and slider (partially obscured)

Figure 4-7. Ext JS window object, date picker, and slider (partially obscured)

The best content for your career. Discover unlimited learning on demand for around $1/day.