HTML5 Zone is brought to you in partnership with:

David Catuhe is a Microsoft HTML5 Evangelist based in Paris, France. He does much of his research on Windows 8, Kinect, and the various HTML5 standards and JS libraries. David is a DZone MVB and is not an employee of DZone and has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

Magic: The Gathering in JavaScript and HTML5

10.24.2011
| 13475 views |
  • submit to reddit

As a user interface fan, I could not miss the development with HTML 5.

So the goal of this post is to walk through a graphic application that uses JavaScript and HTML 5. We will see through examples one way (among others) to develop this kind of project.

Application overview image_thumb6 
Tools 
The HTML 5 page
Data gathering 
Cards loading & cache handling
Cards display
Mouse management  
State storage
Animations
Handling multi-devices
Conclusion
To go further

 

Application overview

We will produce an application that will let us display a Magic the Gathering ©(courtesy of www.wizards.com/Magic) cards collection. Users will be able to scroll and zoom using the mouse (like Bing Maps, for example).

image

You can see the final result here: http://bolaslenses.catuhe.com

The project source files can be downloaded here: http://www.catuhe.com/msdn/bolaslenses.zip

Cards are stored on Windows Azure Storage and use the Azure Content Distribution Network (CDN : a service that deploys data near the final users) in order to achieve maximum performances. An ASP.NET service is used to return cards list (using JSON format). 

image

Tools

To write our application, we will use Visual Studio 2010 SP1 with Web Standards Update. This extension adds IntelliSense support in HTML 5 page (which is a really important thing Sourire).

So, our solution will contain an HTML 5 page side by side with .js files (these files will contain JavaScript scripts). About debug, it is possible to set a breakpoint directly in the .js files under Visual Studio. It is also possible to use the developer bar of Internet Explorer 9 (use F12 key to display it).

image

Debug with Visual Studio 2010

image

Debug with Internet Explorer 9 (F12/Developer bar)

So, we have a modern developer environment with IntelliSense and debug support. Therefore, we are ready to start and first of all, we will write the HTML 5 page.

image

 

The HTML 5 page

Our page will be built around an HTML 5 canvas which will be used to draw the cards:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>Bolas Lenses</title>
        <link href="Content/full.css" rel="stylesheet" type="text/css" />
        <link href="Content/mobile.css" rel="stylesheet" type="text/css" media="screen and (max-width: 480px)" />
        <link href="Content/mobile.css" rel="stylesheet" type="text/css" media="screen and (max-device-width: 480px)" />
        <script src="Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    </head>
    <body>
        <header>
            <div id="legal">
                Cards scanned by <a href="http://www.slightlymagic.net/">MWSHQ Team</a><br />
                Magic the Gathering official site : <a href="http://www.wizards.com/Magic/TCG/Article.aspx?x=mtg/tcg/products/allproducts">
                    http://www.wizards.com/Magic</a>
                <div id="cardsCount">
                </div>
            </div>
            <div id="leftHeader">
                <img id="pictureCell" src="/Content/MTG Black.png" alt="Bolas logo" id="bolasLogo" />
                <div id="title">
                    Bolas Lenses
                </div>
            </div>
        </header>
        <section>
            <img src="Content/Back.jpg" style="display: none" id="backImage" alt="backImage"
                width="128" height="128" />
            <canvas id="mainCanvas">
                        Your browser does not support HTML5 canvas.
            </canvas>
            <div id="stats" class="tooltip">
            </div>
            <div id="waitText" class="tooltip">
                Loading data...
            </div>
        </section>
        <!--Scripts-->
        <script src="Bolas/bolasLenses.animations.js" type="text/javascript"></script>
        <script src="Bolas/bolasLenses.mouse.js" type="text/javascript"></script>
        <script src="Bolas/bolasLenses.cache.js" type="text/javascript"></script>
        <script src="Bolas/bolasLenses.js" type="text/javascript"></script>
    </body>
    </html>

 If we dissect this page, we can note that it is divided into two parts:

  • The header part with the title, the logo and the special mentions
  • The main part (section) holds the canvas and the tooltips that will display the status of the application. There is also a hidden image (backImage) used as source for not yet loaded cards.

To build the layout of the page, a style sheet (full.css) is applied. Style sheets are a mechanism used to change the tags styles (in HTML, a style defines the entire display options for a tag):

    html, body
    {
        height: 100%;
    }
     
    body
    {
        background-color: #888888;
        font-size: .85em;
        font-family: "Segoe UI, Trebuchet MS" , Verdana, Helvetica, Sans-Serif;
        margin: 0;
        padding: 0;
        color: #696969;
    }
     
    a:link
    {
        color: #034af3;
        text-decoration: underline;
    }
     
    a:visited
    {
        color: #505abc;
    }
     
    a:hover
    {
        color: #1d60ff;
        text-decoration: none;
    }
     
    a:active
    {
        color: #12eb87;
    }
     
    header, footer, nav, section
    {
        display: block;
    }
     
    table
    {
        width: 100%;
    }
     
    header, #header
    {
        position: relative;
        margin-bottom: 0px;
        color: #000;
        padding: 0;
    }
     
    #title
    {
        font-weight: bold;
        color: #fff;
        border: none;
        font-size: 60px !important;
        vertical-align: middle;
        margin-left: 70px
    }
     
    #legal
    {
        text-align: right;
        color: white;
        font-size: 14px;
        width: 50%;
        position: absolute;
        top: 15px;
        right: 10px
    }
     
    #leftHeader
    {
        width: 50%;
        vertical-align: middle;
    }
     
    section
    {
        margin: 20px 20px 20px 20px;
    }
     
        #mainCanvas{
        border: 4px solid #000000;
    }
     
    #cardsCount
    {
        font-weight: bolder;
        font-size: 1.1em;
    }
     
    .tooltip
    {
        position: absolute;
        bottom: 5px;
        color: black;
        background-color: white;
        margin-right: auto;
        margin-left: auto;
        left: 35%;
        right: 35%;
        padding: 5px;
        width: 30%;
        text-align: center;
        border-radius: 10px;
        -webkit-border-radius: 10px;
        -moz-border-radius: 10px;
        box-shadow: 2px 2px 2px #333333;
    }
     
    #bolasLogo
    {
        width: 64px;
        height: 64px;
    }
     
    #pictureCell
    {
        float: left;
        width: 64px;
        margin: 5px 5px 5px 5px;
        vertical-align: middle;
    }

 

Thus, this sheet is responsible for setting up the following display:

untitled

Style sheets are powerful tools that allow an infinite number of displays. However, they are sometimes complicated to setup (for example if a tag is affected by a class, an identifier and its container). To simplify this setup, the development bar of Internet Explorer 9 is particularly useful because we can use it to see styles hierarchy that is applied to a tag.
For example let’s take a look at the waitText tooltip with the development bar. To do this, you must press F12 in Internet Explorer and use the selector to choose the tooltip:

imageOnce the selection is done, we can see the styles hierarchy:

image

Thus, we can see that our div received its styles from the body tag  and the .tooltip entry of the style sheet.

With this tool, it becomes possible to see the effect of each style (which can be disabled). It is also possible to add new style on the fly.

Another important point of this window is the ability to change the rendering mode of Internet Explorer 9. Indeed, we can test how, for example, Internet Explorer 8 will handle the same page. To do this, go to the [Browser mode] menu and select the engine of Internet Explorer 8. This change will especially impact our tooltip as it uses border-radius (rounded edge) and box-shadow that are features of CSS 3:


image image

Internet Explorer 9

Internet Explorer 8

Our page provides a graceful degradation  as it still works (with no annoying visual difference) when the browser does not support all the required technologies.

Now that our interface is ready, we will take a look at the data source to retrieve the cards to display.

The server provides the cards list using JSON format on this URL:

http://bolaslenses.catuhe.com/Home/ListOfCards/?colorString=0

It takes one parameter (colorString) to select a specific color (0 = all).

When developing with JavaScript, there is a good reflex to have (reflex also good in other languages too, but really important in JavaScript): one must ask whether what we want to develop has not been already done in an existing framework.

Indeed, there is a multitude of open source projects around JavaScript. One of them is jQuery which provides a plethora of convenient services.

Thus, in our case to connect to the URL of our server and get the cards list, we could go through a XmlHttpRequest and have fun to parse the returned JSON. Or we can use jQuery Sourire.

So we will use the getJSON function which will take care of everything for us:

    function getListOfCards() {
        var url = "http://bolaslenses.catuhe.com/Home/ListOfCards/?jsoncallback=?";
        $.getJSON(url, { colorString: "0" }, function (data) {
            listOfCards = data;
            $("#cardsCount").text(listOfCards.length + " cards displayed");
            $("#waitText").slideToggle("fast");
        });
    }

As we can see, our function stores the cards list in the listOfCards variable and calls two jQuery functions:

  • text that change the text of a tag
  • slideToggle that hides (or shows) a tag by animating its height

The listOfCards list contains objects whose format is:

  • ID: unique identifier of the card
  • Path: relative path of the card (without the extension)

It should be noted that the URL of the server is called with the “?jsoncallback=?” suffix. Indeed, Ajax calls are constrained in terms of security to connect only to the same address as the calling script. However, there is a solution called JSONP that will allow us to make a concerted call to the server (which of course must be aware of the operation). And fortunately, jQuery can handle it all alone by just adding the right suffix.

Once we have our cards list, we can set up the pictures loading and caching.

Cards loading & cache handling

The main trick of our application is to draw only the cards effectively visible on the screen. The display window is defined by a zoom level and an offset (x, y) in the overall system.


    var visuControl = { zoom : 0.25, offsetX : 0, offsetY : 0 };

 

 

image

The overall system is defined by 14819 cards that are spread over 200 columns and 75 rows.

Also, we must be aware that each card is available in three versions:

  • High definition: 480x680 without compression (.jpg suffix)
  • Medium definition: 240x340 with standard compression (.50.jpg suffix)
  • Low definition: 120x170 with strong compression (.25.jpg suffix)

Thus, depending on the zoom level, we will load the correct version to optimize networks transfer.

To do this we will develop a function that will give an image for a given card. This function will be configured to download a certain level of quality. In addition it will be linked with lower quality level to return it if the card for the current level is not yet uploaded:

    function imageCache(substr, replacementCache) {
        var extension = substr;
        var backImage = document.getElementById("backImage");
     
     
        this.load = function (card) {
            var localCache = this;
     
            if (this[card.ID] != undefined)
                return;
     
            var img = new Image();
            localCache[card.ID] = { image: img, isLoaded: false };
            currentDownloads++;
     
            img.onload = function () {
                localCache[card.ID].isLoaded = true;
                currentDownloads--;
            };
     
            img.onerror = function() {
                currentDownloads--;
            };
            
            img.src = "http://az30809.vo.msecnd.net/" + card.Path + extension;
        };
     
        this.getReplacementFromLowerCache = function (card) {
            if (replacementCache == undefined)
                return backImage;
     
            return replacementCache.getImageForCard(card);
        };
     
        this.getImageForCard = function(card) {
            var img;
            if (this[card.ID] == undefined) {
                this.load(card);
     
                img = this.getReplacementFromLowerCache(card);
            }
            else {
                if (this[card.ID].isLoaded)
                    img = this[card.ID].image;
                else
                    img = this.getReplacementFromLowerCache(card);
            }
     
            return img;
        };
    }

An ImageCache is built by giving the associated suffix and the underlying cache.

Here you can see two important functions:

  • load: this function will load the right picture and will store it in a cache (the msecnd.net url is the Azure CDN address of the cards)
  • getImageForCard: this function returns the card picture from the cache if already loaded. Otherwise it requests the underlying cache to return its version (and so on)

So to handle our 3 levels of caches, we have to declare three variables:

    var imagesCache25 = new imageCache(".25.jpg");
    var imagesCache50 = new imageCache(".50.jpg", imagesCache25);
    var imagesCacheFull = new imageCache(".jpg", imagesCache50);

 Selecting the right cover is only depending on zoom:

 

    function getCorrectImageCache() {
        if (visuControl.zoom <= 0.25)
            return imagesCache25;
     
        if (visuControl.zoom <= 0.8)
            return imagesCache50;
     
        return imagesCacheFull;
    }

To give a feedback to the user, we will add a timer that will manage a tooltip that indicates the number of images currently loaded:

    function updateStats() {
        var stats = $("#stats");
     
        stats.html(currentDownloads + " card(s) currently downloaded.");
     
        if (currentDownloads == 0 && statsVisible) {
            statsVisible = false;
            stats.slideToggle("fast");
        }
        else if (currentDownloads > 1 && !statsVisible) {
            statsVisible = true;
            stats.slideToggle("fast");
        }
    }
     
    setInterval(updateStats, 200);

Again we note the use of jQuery to simplify animations.

We will now discuss the display of cards.

Cards display

To draw our cards, we need to actually fill the canvas using its 2D context (which exists only if the browser supports HTML 5 canvas):

    var mainCanvas = document.getElementById("mainCanvas");
    var drawingContext = mainCanvas.getContext('2d');

The drawing will be made by processListOfCards function (called 60 times per second):

    function processListOfCards() {
     
        if (listOfCards == undefined) {
            drawWaitMessage();
            return;
        }
     
        mainCanvas.width = document.getElementById("center").clientWidth;
        mainCanvas.height = document.getElementById("center").clientHeight;
        totalCards = listOfCards.length;
     
        var localCardWidth = cardWidth * visuControl.zoom;
        var localCardHeight = cardHeight * visuControl.zoom;
     
        var effectiveTotalCardsInWidth = colsCount * localCardWidth;
     
        var rowsCount = Math.ceil(totalCards / colsCount);
        var effectiveTotalCardsInHeight = rowsCount * localCardHeight;
     
        initialX = (mainCanvas.width - effectiveTotalCardsInWidth) / 2.0 - localCardWidth / 2.0;
        initialY = (mainCanvas.height - effectiveTotalCardsInHeight) / 2.0 - localCardHeight / 2.0;
     
        // Clear
        clearCanvas();
     
        // Computing of the viewing area
        var initialOffsetX = initialX + visuControl.offsetX * visuControl.zoom;
        var initialOffsetY = initialY + visuControl.offsetY * visuControl.zoom;
     
        var startX = Math.max(Math.floor(-initialOffsetX / localCardWidth) - 1, 0);
        var startY = Math.max(Math.floor(-initialOffsetY / localCardHeight) - 1, 0);
     
        var endX = Math.min(startX + Math.floor((mainCanvas.width - initialOffsetX - startX * localCardWidth) / localCardWidth) + 1, colsCount);
        var endY = Math.min(startY + Math.floor((mainCanvas.height - initialOffsetY - startY * localCardHeight) / localCardHeight) + 1, rowsCount);
     
        // Getting current cache
        var imageCache = getCorrectImageCache();
     
        // Render
        for (var y = startY; y < endY; y++) {
            for (var x = startX; x < endX; x++) {
                var localX = x * localCardWidth + initialOffsetX;
                var localY = y * localCardHeight + initialOffsetY;
     
                // Clip
                if (localX > mainCanvas.width)
                    continue;
     
                if (localY > mainCanvas.height)
                    continue;
     
                if (localX + localCardWidth < 0)
                    continue;
     
                if (localY + localCardHeight < 0)
                    continue;
     
                var card = listOfCards[x + y * colsCount];
     
                if (card == undefined)
                    continue;
     
                // Get from cache
                var img = imageCache.getImageForCard(card);
     
                // Render
                try {
     
                    if (img != undefined)
                        drawingContext.drawImage(img, localX, localY, localCardWidth, localCardHeight);
                } catch (e) {
                    $.grep(listOfCards, function (item) {
                        return item.image != img;
                    });
     
                }
            }
        };
     
        // Scroll bars
        drawScrollBars(effectiveTotalCardsInWidth, effectiveTotalCardsInHeight, initialOffsetX, initialOffsetY);
     
        // FPS
        computeFPS();
    }

This function is built around many key points:

  • If the cards list is not yet loaded, we display a tooltip indicating that download is in progress:

var pointCount = 0;
 
function drawWaitMessage() {
    pointCount++;
 
    if (pointCount > 200)
        pointCount = 0;
 
    var points = "";
 
    for (var index = 0; index < pointCount / 10; index++)
        points += ".";
 
    $("#waitText").html("Loading...Please wait<br>" + points);

  • Subsequently, we define the position of the display window (in terms of cards and coordinates), then we proceed to clean the canvas:

    function clearCanvas() {
        mainCanvas.width = document.body.clientWidth - 50;
        mainCanvas.height = document.body.clientHeight - 140;
     
        drawingContext.fillStyle = "rgb(0, 0, 0)";
        drawingContext.fillRect(0, 0, mainCanvas.width, mainCanvas.height);
    }

 

  • Then we browse the cards list and call the drawImage function of the canvas context. The current image is provided by the active cache (depending on the zoom):

    // Get from cache
    var img = imageCache.getImageForCard(card);
     
    // Render
    try {
     
        if (img != undefined)
            drawingContext.drawImage(img, localX, localY, localCardWidth, localCardHeight);
    } catch (e) {
        $.grep(listOfCards, function (item) {
            return item.image != img;
        });

  • We also have to draw the scroll bar with the RoundedRectangle function that uses quadratic curves:

    function roundedRectangle(x, y, width, height, radius) {
        drawingContext.beginPath();
        drawingContext.moveTo(x + radius, y);
        drawingContext.lineTo(x + width - radius, y);
        drawingContext.quadraticCurveTo(x + width, y, x + width, y + radius);
        drawingContext.lineTo(x + width, y + height - radius);
        drawingContext.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        drawingContext.lineTo(x + radius, y + height);
        drawingContext.quadraticCurveTo(x, y + height, x, y + height - radius);
        drawingContext.lineTo(x, y + radius);
        drawingContext.quadraticCurveTo(x, y, x + radius, y);
        drawingContext.closePath();
        drawingContext.stroke();
        drawingContext.fill();
    }

    function drawScrollBars(effectiveTotalCardsInWidth, effectiveTotalCardsInHeight, initialOffsetX, initialOffsetY) {
        drawingContext.fillStyle = "rgba(255, 255, 255, 0.6)";
        drawingContext.lineWidth = 2;
     
        // Vertical
        var totalScrollHeight = effectiveTotalCardsInHeight + mainCanvas.height;
        var scaleHeight = mainCanvas.height - 20;
        var scrollHeight = mainCanvas.height / totalScrollHeight;
        var scrollStartY = (-initialOffsetY + mainCanvas.height * 0.5) / totalScrollHeight;
        roundedRectangle(mainCanvas.width - 8, scrollStartY * scaleHeight + 10, 5, scrollHeight * scaleHeight, 4);
     
        // Horizontal
        var totalScrollWidth = effectiveTotalCardsInWidth + mainCanvas.width;
        var scaleWidth = mainCanvas.width - 20;
        var scrollWidth = mainCanvas.width / totalScrollWidth;
        var scrollStartX = (-initialOffsetX + mainCanvas.width * 0.5) / totalScrollWidth;
        roundedRectangle(scrollStartX * scaleWidth + 10, mainCanvas.height - 8, scrollWidth * scaleWidth, 5, 4);
    }

  • And finally, we need to compute the number of frames per second:

    function computeFPS() {
        if (previous.length > 60) {
            previous.splice(0, 1);
        }
        var start = (new Date).getTime();
        previous.push(start);
        var sum = 0;
     
        for (var id = 0; id < previous.length - 1; id++) {
            sum += previous[id + 1] - previous[id];
        }
     
        var diff = 1000.0 / (sum / previous.length);
     
        $("#cardsCount").text(diff.toFixed() + " fps. " + listOfCards.length + " cards displayed");
    }

  • Drawing cards relies heavily on the browser's ability to speed up canvas rendering. For the record, here are the performances on my machine with the minimum zoom level (0.05):

image

 

Browser

FPS

Internet Explorer 9 30
Firefox 5 30
Chrome 12 17
iPad (with a zoom level of 0.8) 7
Windows Phone Mango (with a zoom level of 0.8) 20 (!!)
The site even works on mobile phones and tablets as long as they support HTML 5.

 

Here we can see the inner power of HTML 5 browsers that can handle a full screen of cards more than 30 times per second!

Mouse management

To browse our cards collection, we have to manage the mouse (including its wheel).

For the scrolling, we'll just handle the onmouvemove, onmouseup and onmousedown events.

Onmouseup and onmousedown events will be used to detect if the mouse is clicked or not:

 

 

    var mouseDown = 0;
    document.body.onmousedown = function (e) {
        mouseDown = 1;
        getMousePosition(e);
     
        previousX = posx;
        previousY = posy;
    };
     
    document.body.onmouseup = function () {
        mouseDown = 0;
    };


The onmousemove event is connected to the canvas and used to move the view:
    var previousX = 0;
    var previousY = 0;
    var posx = 0;
    var posy = 0;
     
    function getMousePosition(eventArgs) {
        var e;
     
        if (!eventArgs)
            e = window.event;
        else {
            e = eventArgs;
        }
     
        if (e.offsetX || e.offsetY) {
            posx = e.offsetX;
            posy = e.offsetY;
        }
        else if (e.clientX || e.clientY) {
            posx = e.clientX;
            posy = e.clientY;
        }        
    }
     
    function onMouseMove(e) {
        if (!mouseDown)
            return;
        getMousePosition(e);
     
        mouseMoveFunc(posx, posy, previousX, previousY);
     
        previousX = posx;
        previousY = posy;
    }

This function (onMouseMove) calculates the current position and provides also the previous value in order to move the offset of the display window:
    function Move(posx, posy, previousX, previousY) {
        currentAddX = (posx - previousX) / visuControl.zoom;
        currentAddY = (posy - previousY) / visuControl.zoom;
    }
    MouseHelper.registerMouseMove(mainCanvas, Move);

Note that jQuery also provides tools to manage mouse events.

For the management of the wheel, we will have to adapt to different browsers that do not behave the same way on this point:


    function wheel(event) {
        var delta = 0;
        if (event.wheelDelta) {
            delta = event.wheelDelta / 120;
            if (window.opera)
                delta = -delta;
        } else if (event.detail) { /** Mozilla case. */
            delta = -event.detail / 3;
        }
        if (delta) {
            wheelFunc(delta);
        }
     
        if (event.preventDefault)
            event.preventDefault();
        event.returnValue = false;
    }
We can see that everyone does what he wants :).

The function to register with this event is:


    MouseHelper.registerWheel = function (func) {
        wheelFunc = func;
     
        if (window.addEventListener)
            window.addEventListener('DOMMouseScroll', wheel, false);
     
        window.onmousewheel = document.onmousewheel = wheel;
    };

And we will use this function to change the zoom with the wheel:
    // Mouse
    MouseHelper.registerWheel(function (delta) {
        currentAddZoom += delta / 500.0;
    });

Finally we will add a bit of inertia when moving the mouse (and the zoom) to give some kind of smoothness:
    // Inertia
    var inertia = 0.92;
    var currentAddX = 0;
    var currentAddY = 0;
    var currentAddZoom = 0;
     
    function doInertia() {
        visuControl.offsetX += currentAddX;
        visuControl.offsetY += currentAddY;
        visuControl.zoom += currentAddZoom;
     
        var effectiveTotalCardsInWidth = colsCount * cardWidth;
     
        var rowsCount = Math.ceil(totalCards / colsCount);
        var effectiveTotalCardsInHeight = rowsCount * cardHeight
     
        var maxOffsetX = effectiveTotalCardsInWidth / 2.0;
        var maxOffsetY = effectiveTotalCardsInHeight / 2.0;
     
        if (visuControl.offsetX < -maxOffsetX + cardWidth)
            visuControl.offsetX = -maxOffsetX + cardWidth;
        else if (visuControl.offsetX > maxOffsetX)
            visuControl.offsetX = maxOffsetX;
     
        if (visuControl.offsetY < -maxOffsetY + cardHeight)
            visuControl.offsetY = -maxOffsetY + cardHeight;
        else if (visuControl.offsetY > maxOffsetY)
            visuControl.offsetY = maxOffsetY;
     
        if (visuControl.zoom < 0.05)
            visuControl.zoom = 0.05;
        else if (visuControl.zoom > 1)
            visuControl.zoom = 1;
     
        processListOfCards();
     
        currentAddX *= inertia;
        currentAddY *= inertia;
        currentAddZoom *= inertia;
     
        // Epsilon
        if (Math.abs(currentAddX) < 0.001)
            currentAddX = 0;
        if (Math.abs(currentAddY) < 0.001)
            currentAddY = 0;
    }

This kind of small function does not cost a lot to implement, but adds a lot to the quality of user experience.

State storage

Also to provide a better user experience, we will save the display window’s position and zoom. To do this, we will use the service of localStorage (which saves pairs of keys / values ​​for the long term (the data is retained after the browser is closed) and only accessible by the current window object):

    function saveConfig() {
        if (window.localStorage == undefined)
            return;
     
        // Zoom
        window.localStorage["zoom"] = visuControl.zoom;
     
        // Offsets
        window.localStorage["offsetX"] = visuControl.offsetX;
        window.localStorage["offsetY"] = visuControl.offsetY;
    }
     
    // Restore data
    if (window.localStorage != undefined) {
        var storedZoom = window.localStorage["zoom"];
        if (storedZoom != undefined)
            visuControl.zoom = parseFloat(storedZoom);
     
        var storedoffsetX = window.localStorage["offsetX"];
        if (storedoffsetX != undefined)
            visuControl.offsetX = parseFloat(storedoffsetX);
     
        var storedoffsetY = window.localStorage["offsetY"];
        if (storedoffsetY != undefined)
            visuControl.offsetY = parseFloat(storedoffsetY);
    }


Animations

To add even more dynamism to our application we will allow our users to double-click on a card to zoom and focus on it.



Our system should animate three values: the two offsets (X, Y) and the zoom. To do this, we will use a function that will be responsible of animating a variable from a source value to a destination value with a given duration:
    var AnimationHelper = function (root, name) {
        var paramName = name;
        this.animate = function (current, to, duration) {
            var offset = (to - current);
            var ticks = Math.floor(duration / 16);
            var offsetPart = offset / ticks;
            var ticksCount = 0;
     
            var intervalID = setInterval(function () {
                current += offsetPart;
                root[paramName] = current;
                ticksCount++;
     
                if (ticksCount == ticks) {
                    clearInterval(intervalID);
                    root[paramName] = to;
                }
            }, 16);
        };
    };

The use of this function is:
    // Prepare animations parameters
    var zoomAnimationHelper = new AnimationHelper(visuControl, "zoom");
    var offsetXAnimationHelper = new AnimationHelper(visuControl, "offsetX");
    var offsetYAnimationHelper = new AnimationHelper(visuControl, "offsetY");
    var speed = 1.1 - visuControl.zoom;
    zoomAnimationHelper.animate(visuControl.zoom, 1.0, 1000 * speed);
    offsetXAnimationHelper.animate(visuControl.offsetX, targetOffsetX, 1000 * speed);
    offsetYAnimationHelper.animate(visuControl.offsetY, targetOffsetY, 1000 * speed);

The advantage of the AnimationHelper function is that it is able to animate as many parameters as you wish (and that only with the setTimer function!)
 

Handling multi-devices


Finally we will ensure that our page can also be seen on tablets PC and even on phones.

To do this, we will use a feature of CSS 3: The media-queries. With this technology, we can apply style sheets according to some queries such as a specific display size:
    
        
    
    

    

Here we see that if the screen width is less than 480 pixels, the following style sheet will be added:

    #legal
    {
        font-size: 8px;    
    }
     
    #title
    {
        font-size: 30px !important;
    }
     
    #waitText
    {
        font-size: 12px;
    }
     
    #bolasLogo
    {
        width: 48px;
        height: 48px;
    }
     
    #pictureCell
    {
        width: 48px;
    }


Finally we will ensure that our page can also be seen on tablets PC and even on phones.

To do this, we will use a feature of CSS 3:

    #legal
    {
        font-size: 8px;    
    }
     
    #title
    {
        font-size: 30px !important;
    }
     
    #waitText
    {
        font-size: 12px;
    }
     
    #bolasLogo
    {
        width: 48px;
        height: 48px;
    }
     
    #pictureCell
    {
        width: 48px;
    }

Conclusion

HTML 5 / CSS 3 / JavaScript and Visual Studio 2010 allow to develop portable and efficient solutions (within the limits of browsers that support HTML 5 of course) with some great features such as hardware accelerated rendering.

This kind of development is also simplified by the use of frameworks like jQuery.

Also, I am especially fan of JavaScript that turns out to be a very powerful dynamic language. Of course, C# or VB.NET developers have to change theirs reflexes but for the development of web pages it's worth.

In conclusion, I think that the best to be convinced is to try!

To go further

 

About the Author

David Catuhe is a developer evangelist for Microsoft France in charge of user experience development tools (from XAML to DirectX/XNA and HTML5). He defines himself as a geek and likes coding all that refer to graphics. Before working for Microsoft, he founded a company that developed a realtime 3D engine written with DirectX (www.vertice.fr).

Source:  http://blogs.msdn.com/b/eternalcoding/archive/2011/07/25/feedback-of-a-graphic-development-using-html5-amp-javascript.aspx

Published at DZone with permission of David Catuhe, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)