Creating a Scrolling Effect

In this post we will create an effect which mimics flowing water as follows:

Note that this effect can also be used to create the appearance of a background scrolling past such as the tree in Chicken Wings, and is used to create both the water in Entombed and the lava in Brimstone.

The concept is simple: take an image, double it in the vertical direction, and use context.drawImage to pull snapshots from it. The steps are as follows:

  1. Create an image called the basis image. Its width w and its height should be the width and height of the desired canvas.
  2. Create a second image scrollImage of width w and height 2h. The upper half of this image is a duplicate of the basis image, and the lower half of this image is also a duplicate of the basis image.
  3. Declare a variable y which keeps track of the scrolling. Initialize it to 0.
  4. Create a function scroll() which does the following:
  • Clears the canvas.
  • Clips a canvas-sized rectangle out of the scrollImage at location (0,y):
    context.drawImage(scrollImage,0,y,canvas.width,canvas.height,0,0,canvas.width,canvas.height);
  • Increments y and uses modulus to ensure it is bound between 0 and the canvas height:
    y++;
    y %= canvas.height;

Once the scroll function is created, call it periodically within a setInterval event.

Games Mentioned in this Post:

Leave a Reply

Your email address will not be published. Required fields are marked *