Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 5. Animation > 5.7. Scrolling the Background

5.7. Scrolling the Background

So far in this chapter, you’ve seen how to animate objects without disturbing the static background underneath. Many animations also animate the backgrounds themselves; for example, you might have drifting clouds, as shown in Figure 5.7, or you might implement an animated background for a side-scroller video game.

image
image
image

Figure 5.7. Simulating drifting clouds: From top to bottom, clouds move right to left

The application shown in Figure 5.7 scrolls the background by translating the canvas’s context, like this:


var SKY_VELOCITY = 30, // 30 pixels/second
    skyOffset = 0;     // Translate by this offset
    ...

function draw() {
   skyOffset = skyOffset < canvas.width ?
               skyOffset + SKY_VELOCITY/fps : 0;

   context.save();
   context.translate(-skyOffset, 0);
   context.drawImage(sky, 0, 0);
   context.drawImage(sky, sky.width, 0);
   context.restore();
}


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint