XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.

advertisement

All Aboard AJAX, HTML Canvas, and the Supertrain
by Dave Hoover | Pages: 1, 2, 3, 4, 5, 6

No trains yet, but our canvas is now redrawing itself every 2,000 milliseconds (aka 2 seconds). On to the good part. I'll represent the trains with images, using canvas' drawImage method. Now that I have window.setInterval handling my periodic executions, I can use Prototype's vanilla Ajax.Request to grab the trains' status. Once I have the data from the server, I update the location of my train images. The following code should animate the trains, showing their real-time progress:

docroot/redwood.html

  var trains = {
    north: new Train("train-lr.png", 5),
    south: new Train("train-rl.png", 60)
  }
  ...
  function updateCanvas() {
    clearScreen()
    drawTracks()

    new Ajax.Request("/train/line",
                     { onComplete: function(request) {
                         var jsonData = eval(request.responseText)
                         if (jsonData == undefined) { return }
                         jsonData.each(function(data) {
                           trains[data.track].update(data.location)
                         })
                       }
                     })
  }
  ...
  function Train(image, y) {
    this.image = new Image()
    this.image.src = image
    this.y = y
    this.update = updateTrain
  }

  function updateTrain(location) {
    canvas.drawImage(this.image, location, this.y)
  }
  ...

Figure 5
Figure 5.

We've pulled several concepts together in this latest step. We have made an asynchronous call using Prototype, received the JSON string in the response and called eval() on it to marshal it into an array of JavaScript objects. We use Train objects to hold the initial train state and update behavior. Unfortunately, the latest code creates an undesirable flicker in the train images. This is caused by the time that elapses between clearing the screen and the AJAX onComplete callback that draws the images. By moving the clearScreen call up to the last possible moment before the trains are drawn, the annoying flicker is removed.

docroot/redwood.html

  ...
  function updateCanvas() {
    new Ajax.Request("/train/line",
                     { onComplete: function(request) {
                         var jsonData = eval(request.responseText)
                         if (jsonData == undefined) { return }
                         clearScreen()
                         jsonData.each(function(data) {
                           trains[data.track].update(data.location)
                         })
                         drawTracks()
                         drawHotspots()
                       }
                     })
  }
  ...

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow