# Documentation and HTML5 examples

Need something that OfficeExcel doesn't currently support? OfficeExcel license holders can usually be accomodated - please contact support to discuss your requirements.

#### Introduction

- Introduction to OfficeExcel: HTML5 Javascript charts library
  - What is HTML5 canvas?

- Example charts
- The OfficeExcel license
- Release notes

#### Chart types

- Bar charts
- Bi-polar charts
- Donut charts
- Fuel charts
- Funnel charts
- Gauge charts
- Gantt charts
- Horizontal bar charts
- Horizontal progress bar
- LED Grid
- Line charts
- Meter charts
- Odometer charts
- Pie charts
- Radar charts
- Rose charts
- Radial scatter charts
- Scatter charts
- Thermometer charts
- Vertical progress bar
- Waterfall charts

#### Basic examples

- A basic example
- A basic example of the OfficeExcel pseudo-events
- A basic example of a charts in tooltips
- A basic example of a combined Bar/Line chart

#### HOWTO Guides

- Make a transition effect
- Add events to your charts
- Add images to your charts
- Add links to your charts
- Use the ModalDialog with events

#### Features and examples

- Pseudo-standard events
- Displaying financial data
- Fetching data from an XML file (AJAX)
- Animation and visual effects
- Variable gutter sizes
- The OfficeExcel.SetConfig() function
- Examples of keys in charts
- Updating your charts dynamically
- Retrieving a PNG of your charts
- DOMContentLoaded example
- Custom OfficeExcel events
- Adjusting your charts interactively
- Using tooltips in your charts
- Resizing your charts
- Microsoft Internet Explorer support
- Asynchronous processing
- Zooming your charts
- Annotating your charts
  - Making your annotations shareable across browsers/computers
- Combining charts
- Integrating OfficeExcel with external libraries (ModalDialog)
- Available CSS classes
- About canvas color definitions
- Context menus

#### Miscellaneous

- Support

- Miscellaneous documentation
- Common issues
- API Documentation

- The changelog
- Backwards compatibility breaks

#### On this page:

- Benefits of OfficeExcel: HTML5 Javascript charts library
- Browser support
- Improving the performance of your charts
- Implementing OfficeExcel
- Suggested structure for OfficeExcel
- Integration with server side scripting
  - Integration with PHP & MySQL
  - Making AJAX requests

## Benefits of OfficeExcel: HTML5 Javascript charts library

The HTML5 canvas tag is a new tag for HTML5. It allows for two dimensional drawing easily using Javascript. This makes it perfect for producing charts. Because Javascript runs on your users' computer, none of the load on your web server normally associated with producing charts is incurred. Not only that but because of the greater processing power that is typically available on users' computers, they will be much faster. And, because the code can be both compressed (for example if you're using Apache, mod_gzip will do this automatically for you) and cached, bandwidth usage can be massively reduced. This makes it economically attractive to employ at the same time as benefiting your website, ie:

- It can save you money by reducing the load on your web server(s)
- It can speed up your web pages

Imagine, you are creating 10,000 charts a day and the data is such that the resulting charts cannot be cached. With the OfficeExcel library you can reduce that figure to zero. All the processing is done by each individual web browser, much like showing the HTML that you send to them. So you don't have to send any images, you simply send them the Javascript charts libraries once. So, much lower bandwidth bills and less strain on your webserver.

And if that wasn't enough, because the charts are created using Javascript, they will work offline if you view a .html page on your own PC. Download the archive and see! Useful if you need to do a presentation (for example) and want to use the same charts as your website.

- Cross browser support.
- 20+ Different base chart types (Examples).
- Charts work on and off-line.
- Interactive features.

- Charts are created on the client - no server overhead.
- Very easy setup (see Implementing OfficeExcel).
- Fully documented.
- Very easy to learn.

## Browser support

Since the charts are produced using HTML5 features (the new canvas tag), client support includes:

- Mozilla Firefox 3.0+
- Google Chrome 1+
- Apple Safari 3+
- Opera 9.5+
- Microsoft Internet Explorer 7+ (see note)
- iPhone (text support from iOS v4+)
- iPad (text support from iOS v4.2+)

The HTML5 canvas tag is part of the HTML5 specification, and all of the above browsers have some sort of support for it.

HTML5 canvas & Microsoft Internet Explorer (MSIE)
Microsoft Internet Explorer 6/7/8 don't natively support the HTML5 canvas tag. To support MSIE 7 and 8 you will need to use either Google Chrome Frame or ExCanvas from Google (which is included in the OfficeExcel archive). Read more about Internet Explorer compatibility here.

Starting from the developer preview 3, Microsoft Internet Explorer 9 has full support for HTML5 canvas.

MSIE 6 is supported using Google Chrome Frame.

OfficeExcel and older browsers
Older browsers (eg Chrome 1, Firefox 3, Safari 3, Opera 9.5) are supported, however if they don't support the canvas shadow or text APIs, these will naturally be unavailable. Earlier versions of these browsers may work, but are untested.

Other devices
Other devices (eg mobile devices) may support or may be intending to support the HTML5 canvas tag as part of their HTML5 support. Typically the newer a device or its OS the higher the likelyhood is that it has support for HTML5 canvas.

## Improving the performance of your charts

Although performance is excellent, (eg compared to server based charts libraries), you may still want to tune OfficeExcel further. The biggest thing you can do is use HTTP compression, which reduces the initial download time of the libraries, but there are a number of things you can do:

- Compression
  HTTP compression can dramatically reduce your bandwidth bills and increase the speed of your website. The OfficeExcel.common.core.js file for example used to be over 100k, but with compression this was reduced to around 17k. Less than a fifth of the original size! If you do only one thing to aid performance, then it should be this.

  To achieve this with Apache you have a few options:

  - You can use the Apache module mod_gzip which compresses the libraries on the fly.
  - You can compress the libraries manually using the Unix gzip command, rename them to remove the .gz suffix and add the header using an Apache directive (eg AddEncoding gzip .js). If you have some sort of release process/script, it would make sense to add this to it to automate the procedure.

- Minification
  Minification reduces the size of the library before compression takes effect, removing unnecessary spaces and comments etc. A combination of minification and compression will give superb results. For example, before being split up into seperate files, minification combined with compression reduced the common library from over 100k to roughly 10k (!). There is a PHP shell script that you can use to minify the libraries in the scripts directory.

  You can get pre-minified versions of the libraries here.

- Pre-emptive caching
  Slightly different to caching itself, is pre-emptive caching. This involves downloading the libraries before the page that requires them is shown. This way, they're already in the users browser cache and the chart will subsequently appear to be much much quicker. An example of this would be having the library included at the bottom of your index page of your website (optionally with the defer="defer" attribute). The script can be downloaded at will because the page doesn't actually use it, but for subsequent pages it will already be in the users browser cache.

- Caching
  Since the libraries you're using won't change that often, you can set distant Expires: headers on them, or appropriate Cache-Control: headers, and the client will not even have to contact your server for it. When you want to make sure the library is re-downloaded (eg. you update the library), then simply change the filename.

- Script tag placement
  According to Yahoo! guidelines placing the <SCRIPT> tag at the bottom of the page can increase the percieved load time. If you do this, then your charts should be created in the window.onload event, otherwise the browser may try to create them without the library having been loaded, and will therefore subsequently fail.

  You should also consider the effect that this has when your page is rather weighty. If the page is weighty there will be a small delay before the onload event fires, and therefore creates the chart. This might not be so bad if the chart is not immediately visible, however if it is then you should carefully consider using the onload event. You may wish to load the library in the page header, define the canvas tag and then immediately define the javascript that creates the chart. This way the chart will be created and shown, and then the rest of the page loads. The end result is that your chart appears to be faster.

  Between the onload event, asychronous Javascript and careful tag placement, you will need to experiment to get the right result for you.
- Document structure
  The structure of your document can have a significant impact on how fast your charts are displayed. If, for example, you use tables for layout, this can delay the display of elements that are affected by the size of the table. Where possible, you should consider trying to convert your layout to DIVs. An example of this is the front page of this website. The charts were right aligned using a table as a container. This caused a visible delay when showing them. In this case it was a simple matter to convert the page to use DIVs, and the page subsequently displays much faster.

- Creating your charts asynchronously
  Where possible, you may wish to create your charts asynchronously. This allows the browser to continue rendering the page immediately after getting to the code that creates the chart. This might not be perceptible if you don't have a lot of charts, or your page is small. You can read a little more about this and see example code here.

  Note that recent releases of Google Chrome (from a dev release of version 4) have had an issue with creating charts asynchronously, which presents itself by not drawing text sometimes (it's not consistent). Simply not using asynchronous chart production in this case resolves the issue.
- DOMContentLoaded event
  Using this event can speed up the display of your charts signifcantly compared to the more well known onload event. It is supported by Chrome, Gecko based browsers (ie Firefox), Safari, Opera and Internet Explorer 9. This event fires when the structure of the page is loaded, but not necessarily the images or CSS. This means that if your page is laden with images, this event will fire before the onload event, thus creating your charts quicker. The effect can be very noticeable.

      function addListener(func)
      {
          if(window.addEventListener) {
              window.addEventListener('DOMContentLoaded', func, false);
          } else {
              document.attachEvent("onDOMContentLoaded", func);
          }
      }

  You can read more about the DOMContentLoaded event on the Mozilla site, here, and the Microsoft site here. There's an example here.

- AJAX requests
  If you can take advantage of AJAX, you can use this method to retrieve data from your server. If, for example, you have a chart that shows ongoing information, instead of simply refreshing the entire page, you could use an AJAX request to just retrieve the data that you want and update the chart that way. This reduces the amount of data needed to be transferred, thus reducing the bandwidth used, and will be quicker than a full page refresh, particularly if your page is weighty. There's a simple AJAX function that you can use below.

- Combining libraries
  You may wish to consider combining the OfficeExcel libraries into a single file. This won't save on the size of the individual libraries, but will save on the headers that are sent as part of the response. If a typical response sends 500 bytes worth of headers, and you send four chart libraries, then combining the libraries would save 1500 bytes. Multiple factors need to be considered though, including things like caching, which can circumvent the unneccessary repeated downloading of the libraries.

  To make your life straight-forward, you may want to make this a part of your release script/process. This way you can make changes to the scripts in your development environment as you would normally.

  Another effect of combining libraries is reducing the amount of HTTP connections needed to retrieve them. Most browsers have a limit on how many connections they can create simultaneously, so if they're not being used to retrieve your chart libraries, they can be used for something else.

- Avoiding shadow blur with animations
  If you're using animations then you may wish to avoid or reduce the shadow blur that you're using. With HTML5 canvas shadow blur is a drain on performance - so if you're looking to get the most out of your charts or are using animations which require redrawing the chart, turning off the shadow blur can reduce the time it takes to draw the charts leading to smoother charts.

A reasonable performance strategy

Although there's a lot you can do in regards to performance, a few of the points here will suffice for most websites:

- Compression
- Minification
- Pre-emptive caching
- Caching

The number one thing you should do is compress your libraries. This has multiple benefits and provides by far the most gain, effectively for free. Secondly, use the minified libraries. Since you can download them here, you might as well use them. Then we have pre-emptive caching. Since most websites won't show charts on the front page or will have a login page that is shown before any charts, this effectively eliminates the charts library download. And lastly caching should be done as a matter of course. There's no reason to keep downloading the same library so even caching for only 30 minutes (or the duration of an average visit to your website) will produce results.

General website performance tools
If your aim is to improve your websites performance as a whole then you may be interested in these tools:

- http://www.webpagetest.org/
  This site can provide a wealth of information about how to improve the permance of your website, specific to your site.
- Page Speed for Google Chrome
  Page Speed for Mozilla Firefox
  Page Speed online
  The Page Speed plugins and the online tool also provide a great deal of information about how to speed up your website.
- Convert images to data: URLs
  A tool which converts images to data: URLs. Using data: URLs can reduce the number of HTTP requests used.

## Implementing OfficeExcel

Getting OfficeExcel up and running is very easy and consists of three steps. If you're having trouble I suggest you get hold of a copy of Firefox along with Firebug - its Javascript error console will make debugging your issue much easier. Many problems are down to a library not having been included or not using the onload event when you need to. You might also benefit from using the Web Developer toolbar for Firefox. This allows you to easily disable caching, thus eliminating any problems that that causes. You could equally use the Chrome developer tools (CTRL+SHIFT+J), optionally in docked mode, which also provides a good quality Javascript console.

1. Include the libraries (put this in your documents <HEAD>):

       <script src="OfficeExcel.common.core.js"></script>

       <script src="OfficeExcel.common.adjusting.js"></script> <!-- Just needed for adjusting -->
       <script src="OfficeExcel.common.annotate.js"></script>  <!-- Just needed for annotating -->
       <script src="OfficeExcel.common.context.js"></script>   <!-- Just needed for context menus -->
       <script src="OfficeExcel.common.effects.js"></script>   <!-- Just needed for visual effects -->
       <script src="OfficeExcel.common.resizing.js"></script>  <!-- Just needed for resizing -->
       <script src="OfficeExcel.common.tooltips.js"></script>  <!-- Just needed for tooltips -->
       <script src="OfficeExcel.common.zoom.js"></script>      <!-- Just needed for zoom -->

       <script src="OfficeExcel.bar.js"></script>              <!-- Just needed for bar charts -->
       <script src="OfficeExcel.bipolar.js"></script>          <!-- Just needed for bi-polar charts -->
       <script src="OfficeExcel.fuel.js"></script>             <!-- Just needed for fuel charts -->
       <script src="OfficeExcel.funnel.js"></script>           <!-- Just needed for funnel charts -->
       <script src="OfficeExcel.gantt.js"></script>            <!-- Just needed for gantt charts -->
       <script src="OfficeExcel.gauge.js"></script>            <!-- Just needed for gauge charts -->
       <script src="OfficeExcel.hbar.js"></script>             <!-- Just needed for horizontal bar charts -->
       <script src="OfficeExcel.hprogress.js"></script>        <!-- Just needed for horizontal progress bars -->
       <script src="OfficeExcel.led.js"></script>              <!-- Just needed for LED charts -->
       <script src="OfficeExcel.line.js"></script>             <!-- Just needed for line charts -->
       <script src="OfficeExcel.meter.js"></script>            <!-- Just needed for meter charts -->
       <script src="OfficeExcel.odo.js"></script>              <!-- Just needed for odometers -->
       <script src="OfficeExcel.pie.js"></script>              <!-- Just needed for pie AND donut charts -->
       <script src="OfficeExcel.radar.js"></script>            <!-- Just needed for radar charts -->
       <script src="OfficeExcel.rose.js"></script>             <!-- Just needed for rose charts -->
       <script src="OfficeExcel.rscatter.js"></script>         <!-- Just needed for rscatter charts -->
       <script src="OfficeExcel.scatter.js"></script>          <!-- Just needed for scatter charts -->
       <script src="OfficeExcel.thermometer.js"></script>      <!-- Just needed for thermometer charts -->
       <script src="OfficeExcel.vprogress.js"></script>        <!-- Just needed for vertical progress bars -->
       <script src="OfficeExcel.waterfall.js"></script>        <!-- Just needed for waterfall charts  -->

2. Add the canvas tag (put it where you want the chart to appear):

       <canvas id="myCanvas" width="600" height="250">[No canvas support]</canvas>

3. Create the chart (since it is using the onload event, you can put this anywhere):

       <script>
           window.onload = function ()
           {
               var data = [280, 45, 133, 166, 84, 259, 266, 960, 219, 311, 67, 89];

               var bar = new OfficeExcel.Bar('myCanvas', data);
               bar.Set('chart.labels', ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']);
               bar.Set('chart.gutter.left', 35);
               bar.Draw();
           }
       </script>

There's also a very basic example of using OfficeExcel, that does very little. It can be helpful to illustrate how you can get OfficeExcel up and running.

## Suggested structure for OfficeExcel

The suggested layout structure for the OfficeExcel libraries is shown on the right. The www.example.com folder represents the root/top level of your website with the javascript directory beneath that. The css and images folders are shown for illustrative purposes only. If you follow this layout then your URLs to the OfficeExcel libraries would be:

http://www.example.com/javascript/OfficeExcel/OfficeExcel.common.core.js
http://www.example.com/javascript/OfficeExcel/OfficeExcel.bar.js
etc

By using this structure you make OfficeExcel easy to update should you need to, and also keep all the OfficeExcel libraries in one, easy to find, place.

## Integration with server side scripting

This is a very easy process, as easy as sending content to the browser. All you need to do is make the data variable (as in the example below) contain the data you want to be displayed. Eg:

    <script src="OfficeExcel.common.core.js"></script>
    <script src="OfficeExcel.line.js"></script>

    <canvas id="myCanvasTag" width="600" height="200">[No canvas support]</canvas>

    <script>
        data = [78,16,26,23,25,51,34,64,84,84];

        line = new OfficeExcel.Line("myCanvasTag", data);
        line.Set("chart.labels", ["Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov"]);
        line.Draw();
    </script>

To get the above using PHP you could do this:

    <?php
        // This simply makes a string out of the array of data
        $myData = join(',', array(78,16,26,23,25,51,34,64,84,84));

        // This prints out the required HTML markup
        print('<script src="OfficeExcel.common.core.js"></script>' . "\n");
        print('<script src="OfficeExcel.line.js"></script>' . "\n\n");
        print('<canvas id="myCanvasTag" width="600" height="200">[No canvas support]</canvas>' . "\n\n");
        print('<script>' . "\n");
        print('    var data = [' . $myData . '];' . "\n\n");
        print('    var line = new OfficeExcel.Line("myCanvasTag", data);' . "\n");
        print('    line.Set("chart.labels", ["Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov"]);' . "\n");
        print('    line.Draw();' . "\n");
        print('</script>');
    ?>

Strictly speaking the var isn't necessary, however if you put the code inside a function (like window.onload), it's probably best to do so as using var will make the variable local, and not global. So doing so will help prevent naming clashes.

#### Integration with PHP & MySQL

This is a simple matter of formatting what you get back from MySQL into a string, as the MySQL dump and PHP code below shows (it's based on a database called OfficeExcel_example):

    #
    # Table structure for table `daily_statistics`
    #

    CREATE TABLE `daily_statistics` (
      `st_day` char(9) NOT NULL,
      `st_statistics` tinyint(4) NOT NULL,
      UNIQUE KEY `st_day` (`st_day`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    #
    # Dumping data for table `daily_statistics`
    #

    INSERT INTO `daily_statistics` VALUES ('Mon', 124);
    INSERT INTO `daily_statistics` VALUES ('Tue', 95);
    INSERT INTO `daily_statistics` VALUES ('Wed', 64);
    INSERT INTO `daily_statistics` VALUES ('Thu', 94);
    INSERT INTO `daily_statistics` VALUES ('Fri', 75);
    INSERT INTO `daily_statistics` VALUES ('Sat', 98);
    INSERT INTO `daily_statistics` VALUES ('Sun', 84);

    <?php
        /**
        * Change these to your own credentials
        */
        $hostname = "localhost";
        $username = "root";
        $password = "PASSWORD";
        $database = "OfficeExcel_example";

        $connection = mysql_connect($hostname, $username, $password) OR die('Could not connect to MySQL: ' . mysql_error());
        mysql_select_db($database);

        $result = mysql_query("SELECT st_day, st_statistics FROM daily_statistics");
        if ($result) {

            $labels = array();
            $data   = array();

            while ($row = mysql_fetch_assoc($result)) {
                $labels[] = $row["st_day"];
                $data[]   = $row["st_statistics"];
            }

            // Now you can aggregate all the data into one string
            $data_string = "[" . join(", ", $data) . "]";
            $labels_string = "['" . join("', '", $labels) . "']";
        } else {
            print('MySQL query failed with error: ' . mysql_error());
        }
    ?>
    <html>
    <head>

        <!-- Don't forget to update these paths -->

        <script src="libraries/OfficeExcel.common.core.js" ></script>
        <script src="libraries/OfficeExcel.line.js" ></script>

    </head>
    <body>

        <canvas id="cvs" width="600" height="250">[No canvas support]</canvas>
        <script>
            chart = new OfficeExcel.Line('cvs', <?php print($data_string) ?>);
            chart.Set('chart.background.grid.autofit', true);
            chart.Set('chart.gutter.left', 35);
            chart.Set('chart.gutter.right', 5);
            chart.Set('chart.hmargin', 10);
            chart.Set('chart.tickmarks', 'endcircle');
            chart.Set('chart.labels', <?php print($labels_string) ?>);
            chart.Draw();
        </script>

    </body>
    </html>

This PHP code provides the data in two strings - $labels_string and $data_string. These variables are then used in the OfficeExcel code to provide the data and the labels.

Remember:

- Change the database hostname/username/password/database to match your own.
- Ensure you have the correct paths to the OfficeExcel libraries.

#### Making AJAX requests

Note: It is important that you're careful with types when making AJAX requests. Since the response is initially a string, and your AJAX function/library may not do conversions for you, you may need to convert these strings to numbers. To do this you can use the Number() or parseInt() functions. For example:

    <script>
        num = Number('23');
        num = parseInt('43');
    </script>

Here is a simple function that you could use to get data from your server using AJAX:

    <script>
        /**
        * Makes an AJAX call. It calls the given callback (a function) when ready
        *
        * @param string   url      The URL to retrieve
        * @param function callback A function object that is called when the response is ready, there's an example below
        *                          called "myCallback".
        */
        function AjaxCall (url, callback)
        {
            // Mozilla, Safari, ...
            if (window.XMLHttpRequest) {
                var httpRequest = new XMLHttpRequest();

            // MSIE
            } else if (window.ActiveXObject) {
                var httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }

            httpRequest.onreadystatechange = callback;

            httpRequest.open('GET', url, true);
            httpRequest.send();
        }

        /**
        * This sample callback function is called when the data is ready (readyState=4)
        */
        function myCallback ()
        {
            if (this.readyState == 4 && this.status == 200) {
                // Everything is good, the response is received
                alert(this.responseText);
            }
        }
    </script>

And you would use it like this:

    <script>
        AjaxCall('http://www.example.com/getSomething.php', myCallback);
    </script>

There's an example here that shows updating your chart dynamically and a fuller example of fetching data with AJAX here.

## Support

If you have a support issue you can send it to the support email address: support@OfficeExcel.net. You can also follow @_OfficeExcel on twitter to get notifications of new releases and notable updates.

If you have a chart that you would like added to the test suite of charts, then feel free to email it to the support address above. The chart should be totally self-contained (ie not rely on external libraries like jQuery). You can think of it this way - free testing! Thanks.